@theengineerscanvas/payment 0.0.0-stage → 0.1.0-rc.16

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/dist/index.js ADDED
@@ -0,0 +1,4822 @@
1
+ import { randomUUID, createHmac, timingSafeEqual, createHash } from 'crypto';
2
+
3
+ // src/public-api/version.ts
4
+ var VERSION = "0.1.0-rc.16";
5
+
6
+ // src/errors/payment-error.ts
7
+ var PaymentError = class extends Error {
8
+ provider;
9
+ providerCode;
10
+ correlationId;
11
+ isRetryable;
12
+ httpStatus;
13
+ meta;
14
+ constructor(message, options = {}) {
15
+ super(message, { cause: options.cause });
16
+ this.name = this.constructor.name;
17
+ this.provider = options.provider;
18
+ this.providerCode = options.providerCode;
19
+ this.correlationId = options.correlationId ?? "unknown";
20
+ this.isRetryable = options.isRetryable ?? false;
21
+ this.httpStatus = options.httpStatus ?? 500;
22
+ this.meta = options.meta;
23
+ }
24
+ };
25
+
26
+ // src/errors/error-codes.ts
27
+ var ErrorCode = {
28
+ CONFIGURATION: "CONFIGURATION",
29
+ VALIDATION: "VALIDATION",
30
+ PROVIDER_UNAVAILABLE: "PROVIDER_UNAVAILABLE",
31
+ NETWORK: "NETWORK",
32
+ TIMEOUT: "TIMEOUT",
33
+ WEBHOOK_VALIDATION: "WEBHOOK_VALIDATION",
34
+ VERIFICATION: "VERIFICATION",
35
+ REFUND: "REFUND",
36
+ PROVIDER: "PROVIDER",
37
+ PROVIDER_BAD_REQUEST: "PROVIDER_BAD_REQUEST",
38
+ PROVIDER_UNAUTHORIZED: "PROVIDER_UNAUTHORIZED",
39
+ PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND",
40
+ PROVIDER_CONFLICT: "PROVIDER_CONFLICT",
41
+ PROVIDER_RATE_LIMIT: "PROVIDER_RATE_LIMIT",
42
+ UNSUPPORTED: "UNSUPPORTED",
43
+ INTERNAL: "INTERNAL"
44
+ };
45
+ var ErrorCategory = {
46
+ CONFIGURATION: "configuration",
47
+ VALIDATION: "validation",
48
+ PROVIDER: "provider",
49
+ NETWORK: "network",
50
+ TIMEOUT: "timeout",
51
+ WEBHOOK: "webhook",
52
+ REFUND: "refund",
53
+ VERIFICATION: "verification",
54
+ UNSUPPORTED: "unsupported",
55
+ INTERNAL: "internal"
56
+ };
57
+
58
+ // src/errors/validation-error.ts
59
+ var ValidationError = class extends PaymentError {
60
+ code = ErrorCode.VALIDATION;
61
+ category = ErrorCategory.VALIDATION;
62
+ httpStatus = 400;
63
+ isRetryable = false;
64
+ constructor(message, options = {}) {
65
+ super(message, { ...options, httpStatus: 400, isRetryable: false });
66
+ }
67
+ };
68
+
69
+ // src/domain/money/currency.ts
70
+ var ISO_4217_RE = /^[A-Z]{3}$/;
71
+ function Currency(value) {
72
+ if (typeof value !== "string" || !ISO_4217_RE.test(value)) {
73
+ throw new ValidationError(`Invalid currency code "${value}": must be a 3-letter ISO 4217 code`);
74
+ }
75
+ return value;
76
+ }
77
+ ((Currency2) => {
78
+ Currency2.NGN = "NGN";
79
+ Currency2.GHS = "GHS";
80
+ Currency2.ZAR = "ZAR";
81
+ Currency2.KES = "KES";
82
+ Currency2.USD = "USD";
83
+ Currency2.EUR = "EUR";
84
+ Currency2.GBP = "GBP";
85
+ })(Currency || (Currency = {}));
86
+
87
+ // src/domain/money/money.ts
88
+ function MinorUnits(value) {
89
+ if (!Number.isFinite(value)) {
90
+ throw new ValidationError("Amount must be a finite number");
91
+ }
92
+ if (!Number.isInteger(value)) {
93
+ throw new ValidationError("Amount must be an integer (minor units)");
94
+ }
95
+ if (value < 0) {
96
+ throw new ValidationError("Amount must not be negative");
97
+ }
98
+ if (value > Number.MAX_SAFE_INTEGER) {
99
+ throw new ValidationError("Amount exceeds maximum safe integer");
100
+ }
101
+ return value;
102
+ }
103
+ function Money(input) {
104
+ return {
105
+ amount: MinorUnits(input.amount),
106
+ currency: Currency(input.currency)
107
+ };
108
+ }
109
+
110
+ // src/domain/reference/payment-reference.ts
111
+ function PaymentReference(raw) {
112
+ if (typeof raw !== "string" || raw.length === 0) {
113
+ throw new ValidationError("Payment reference must be a non-empty string");
114
+ }
115
+ if (!/^[A-Za-z0-9._=,+\-]{6,100}$/.test(raw)) {
116
+ throw new ValidationError(
117
+ `Payment reference must be 6-100 characters, containing only alphanumeric characters, hyphens, underscores, dots, equals, commas, and plus signs (got length ${raw.length})`
118
+ );
119
+ }
120
+ return raw;
121
+ }
122
+
123
+ // src/domain/provider/provider.ts
124
+ var PROVIDER_RE = /^[a-z][a-z0-9_]*$/;
125
+ function Provider(value) {
126
+ if (typeof value !== "string" || value.length === 0) {
127
+ throw new ValidationError("Provider must be a non-empty string");
128
+ }
129
+ if (!PROVIDER_RE.test(value)) {
130
+ throw new ValidationError(
131
+ `Invalid provider name "${value}": must start with a lowercase letter and contain only lowercase letters, digits, and underscores`
132
+ );
133
+ }
134
+ return value;
135
+ }
136
+
137
+ // src/shared/result/result.ts
138
+ function ok(value) {
139
+ return { ok: true, value };
140
+ }
141
+ function err(error) {
142
+ return { ok: false, error };
143
+ }
144
+ async function attempt(fn) {
145
+ try {
146
+ const value = await fn();
147
+ return ok(value);
148
+ } catch (e) {
149
+ return err(e instanceof Error ? e : new Error(String(e)));
150
+ }
151
+ }
152
+
153
+ // src/errors/configuration-error.ts
154
+ var ConfigurationError = class extends PaymentError {
155
+ code = ErrorCode.CONFIGURATION;
156
+ category = ErrorCategory.CONFIGURATION;
157
+ httpStatus = 500;
158
+ isRetryable = false;
159
+ constructor(message, options = {}) {
160
+ super(message, { ...options, httpStatus: 500, isRetryable: false });
161
+ }
162
+ };
163
+
164
+ // src/errors/provider-error.ts
165
+ var ProviderError = class extends PaymentError {
166
+ code = ErrorCode.PROVIDER;
167
+ category = ErrorCategory.PROVIDER;
168
+ httpStatus;
169
+ isRetryable;
170
+ constructor(message, options = {}) {
171
+ const status = options.httpStatus ?? 502;
172
+ const retryable = options.isRetryable ?? false;
173
+ super(message, { ...options, httpStatus: status, isRetryable: retryable });
174
+ this.httpStatus = status;
175
+ this.isRetryable = retryable;
176
+ }
177
+ };
178
+ var ProviderBadRequestError = class extends ProviderError {
179
+ code = ErrorCode.PROVIDER_BAD_REQUEST;
180
+ httpStatus = 400;
181
+ isRetryable = false;
182
+ constructor(message, options = {}) {
183
+ super(message, { ...options, httpStatus: 400, isRetryable: false });
184
+ }
185
+ };
186
+ var ProviderUnauthorizedError = class extends ProviderError {
187
+ code = ErrorCode.PROVIDER_UNAUTHORIZED;
188
+ httpStatus;
189
+ isRetryable = false;
190
+ constructor(message, options = {}) {
191
+ const status = options.httpStatus ?? 401;
192
+ super(message, { ...options, httpStatus: status, isRetryable: false });
193
+ this.httpStatus = status;
194
+ }
195
+ };
196
+ var ProviderNotFoundError = class extends ProviderError {
197
+ code = ErrorCode.PROVIDER_NOT_FOUND;
198
+ httpStatus = 404;
199
+ isRetryable = false;
200
+ constructor(message, options = {}) {
201
+ super(message, { ...options, httpStatus: 404, isRetryable: false });
202
+ }
203
+ };
204
+ var ProviderConflictError = class extends ProviderError {
205
+ code = ErrorCode.PROVIDER_CONFLICT;
206
+ httpStatus = 409;
207
+ isRetryable = false;
208
+ constructor(message, options = {}) {
209
+ super(message, { ...options, httpStatus: 409, isRetryable: false });
210
+ }
211
+ };
212
+ var ProviderRateLimitError = class extends ProviderError {
213
+ code = ErrorCode.PROVIDER_RATE_LIMIT;
214
+ httpStatus = 429;
215
+ isRetryable = true;
216
+ constructor(message, options = {}) {
217
+ super(message, { ...options, httpStatus: 429, isRetryable: true });
218
+ }
219
+ };
220
+
221
+ // src/errors/provider-unavailable-error.ts
222
+ var ProviderUnavailableError = class extends PaymentError {
223
+ code = ErrorCode.PROVIDER_UNAVAILABLE;
224
+ category = ErrorCategory.PROVIDER;
225
+ httpStatus = 502;
226
+ isRetryable = true;
227
+ constructor(message, options = {}) {
228
+ super(message, { ...options, httpStatus: 502, isRetryable: true });
229
+ }
230
+ };
231
+
232
+ // src/errors/unsupported-provider-error.ts
233
+ var UnsupportedProviderError = class extends PaymentError {
234
+ code = ErrorCode.UNSUPPORTED;
235
+ category = ErrorCategory.UNSUPPORTED;
236
+ constructor(message, options = {}) {
237
+ super(message, { ...options, httpStatus: options.httpStatus ?? 501, isRetryable: false });
238
+ }
239
+ };
240
+
241
+ // src/errors/network-error.ts
242
+ var NetworkError = class extends PaymentError {
243
+ code = ErrorCode.NETWORK;
244
+ category = ErrorCategory.NETWORK;
245
+ httpStatus = 502;
246
+ isRetryable = true;
247
+ constructor(message, options = {}) {
248
+ super(message, { ...options, httpStatus: 502, isRetryable: true });
249
+ }
250
+ };
251
+
252
+ // src/errors/timeout-error.ts
253
+ var TimeoutError = class extends PaymentError {
254
+ code = ErrorCode.TIMEOUT;
255
+ category = ErrorCategory.TIMEOUT;
256
+ httpStatus = 504;
257
+ isRetryable = true;
258
+ constructor(message, options = {}) {
259
+ super(message, { ...options, httpStatus: 504, isRetryable: true });
260
+ }
261
+ };
262
+
263
+ // src/errors/webhook-validation-error.ts
264
+ var WebhookValidationError = class extends PaymentError {
265
+ code = ErrorCode.WEBHOOK_VALIDATION;
266
+ category = ErrorCategory.WEBHOOK;
267
+ httpStatus = 401;
268
+ isRetryable = false;
269
+ constructor(message, options = {}) {
270
+ super(message, { ...options, httpStatus: 401, isRetryable: false });
271
+ }
272
+ };
273
+
274
+ // src/errors/verification-error.ts
275
+ var VerificationError = class extends PaymentError {
276
+ code = ErrorCode.VERIFICATION;
277
+ category = ErrorCategory.VERIFICATION;
278
+ httpStatus = 422;
279
+ isRetryable = false;
280
+ constructor(message, options = {}) {
281
+ super(message, { ...options, httpStatus: 422, isRetryable: false });
282
+ }
283
+ };
284
+
285
+ // src/errors/refund-error.ts
286
+ var RefundError = class extends PaymentError {
287
+ code = ErrorCode.REFUND;
288
+ category = ErrorCategory.REFUND;
289
+ httpStatus = 402;
290
+ isRetryable = false;
291
+ constructor(message, options = {}) {
292
+ super(message, { ...options, httpStatus: 402, isRetryable: false });
293
+ }
294
+ };
295
+
296
+ // src/errors/internal-error.ts
297
+ var InternalError = class extends PaymentError {
298
+ code = ErrorCode.INTERNAL;
299
+ category = ErrorCategory.INTERNAL;
300
+ httpStatus = 500;
301
+ isRetryable = false;
302
+ constructor(message, options = {}) {
303
+ super(message, { ...options, httpStatus: 500, isRetryable: false });
304
+ }
305
+ };
306
+
307
+ // src/infrastructure/providers/provider-factory.ts
308
+ var registry = /* @__PURE__ */ new Map();
309
+ function registerProvider(id, factory) {
310
+ if (registry.has(id)) {
311
+ throw new ConfigurationError(`Provider "${id}" is already registered`);
312
+ }
313
+ registry.set(id, factory);
314
+ }
315
+ function createProviderFactory() {
316
+ return {
317
+ create(id, config, deps) {
318
+ const factory = registry.get(id);
319
+ if (!factory) {
320
+ throw new ConfigurationError(
321
+ `Unknown provider "${id}". Available providers: ${[...registry.keys()].join(", ") || "none"}`
322
+ );
323
+ }
324
+ if (config.enabled === false) {
325
+ throw new ConfigurationError(`Provider "${id}" is disabled in configuration`);
326
+ }
327
+ return factory(config, deps);
328
+ },
329
+ supported() {
330
+ return [...registry.keys()];
331
+ }
332
+ };
333
+ }
334
+
335
+ // src/shared/errors/mapper-error.ts
336
+ function mapMapperError(e, options) {
337
+ if (e instanceof ProviderError || e instanceof VerificationError) {
338
+ return e;
339
+ }
340
+ return new ProviderError(
341
+ `Failed to parse ${options.context}: ${e instanceof Error ? e.message : String(e)}`,
342
+ {
343
+ provider: options.provider,
344
+ httpStatus: 502,
345
+ isRetryable: false
346
+ }
347
+ );
348
+ }
349
+
350
+ // src/infrastructure/providers/paystack/paystack-primitives.ts
351
+ function toPaystackDate(...candidates) {
352
+ for (const candidate of candidates) {
353
+ if (candidate === null || candidate === void 0 || candidate === "") continue;
354
+ const date = new Date(candidate);
355
+ if (!Number.isNaN(date.getTime())) return date;
356
+ }
357
+ return void 0;
358
+ }
359
+
360
+ // src/infrastructure/providers/paystack/paystack-mapper.ts
361
+ var PAYSTACK = Provider("paystack");
362
+ function transactionIdOf(transaction) {
363
+ if (transaction === null || transaction === void 0) return void 0;
364
+ if (typeof transaction === "number") return Number.isFinite(transaction) ? String(transaction) : void 0;
365
+ const id = transaction.id;
366
+ return typeof id === "number" && Number.isFinite(id) ? String(id) : void 0;
367
+ }
368
+ function requireTimestamp(candidates, context) {
369
+ const date = toPaystackDate(...candidates);
370
+ if (!date) {
371
+ throw new ProviderError(`Paystack returned ${context} without a usable timestamp`, {
372
+ provider: PAYSTACK,
373
+ httpStatus: 422,
374
+ isRetryable: false
375
+ });
376
+ }
377
+ return date;
378
+ }
379
+ function mapPaystackStatus(status, tx) {
380
+ switch (status) {
381
+ case "abandoned":
382
+ return { kind: "abandoned" };
383
+ case "success":
384
+ return {
385
+ kind: "success",
386
+ paidAt: requireTimestamp([tx.paid_at, tx.updated_at, tx.created_at], "a successful transaction")
387
+ };
388
+ case "failed":
389
+ return {
390
+ kind: "failed",
391
+ reason: tx.gateway_response ?? "payment_failed",
392
+ failedAt: requireTimestamp([tx.updated_at, tx.created_at], "a failed transaction")
393
+ };
394
+ case "pending":
395
+ case "processing":
396
+ case "ongoing":
397
+ case "queued":
398
+ return { kind: "pending" };
399
+ case "reversed":
400
+ return {
401
+ kind: "refunded",
402
+ refundedAt: requireTimestamp([tx.updated_at, tx.created_at], "a reversed transaction"),
403
+ // Paystack exposes no refund id on a reversed transaction.
404
+ refundId: "unknown"
405
+ };
406
+ default:
407
+ return { kind: "pending" };
408
+ }
409
+ }
410
+ function emptyMetadata() {
411
+ return Object.freeze({});
412
+ }
413
+ function mapPaystackCustomer(pc) {
414
+ const name = [pc.first_name, pc.last_name].filter(Boolean).join(" ") || void 0;
415
+ return {
416
+ id: String(pc.id),
417
+ email: pc.email,
418
+ phone: pc.phone,
419
+ name,
420
+ metadata: pc.metadata ? Object.freeze({ ...pc.metadata }) : emptyMetadata()
421
+ };
422
+ }
423
+ function mapAuthorization(auth, tx) {
424
+ return {
425
+ id: auth.authorization_code,
426
+ status: {
427
+ kind: "success",
428
+ paidAt: requireTimestamp(
429
+ [tx.paid_at, tx.updated_at, tx.created_at],
430
+ "an authorization attempt"
431
+ )
432
+ },
433
+ channel: auth.channel,
434
+ bin: auth.bin,
435
+ last4: auth.last4,
436
+ bank: auth.bank,
437
+ authorizationCode: auth.authorization_code,
438
+ attemptedAt: requireTimestamp(
439
+ [tx.paid_at, tx.updated_at, tx.created_at],
440
+ "an authorization attempt"
441
+ )
442
+ };
443
+ }
444
+ function mapPaystackTransactionToPayment(tx) {
445
+ const amount = Money({ amount: tx.amount, currency: tx.currency });
446
+ const status = mapPaystackStatus(tx.status, tx);
447
+ const customer = mapPaystackCustomer(tx.customer);
448
+ const reference = PaymentReference(tx.reference);
449
+ const attempts = [];
450
+ if (tx.authorization) {
451
+ attempts.push(mapAuthorization(tx.authorization, tx));
452
+ }
453
+ const fees = tx.fees != null ? Money({ amount: tx.fees, currency: tx.currency }) : void 0;
454
+ const net = fees && tx.amount - fees.amount >= 0 ? Money({ amount: tx.amount - fees.amount, currency: tx.currency }) : void 0;
455
+ return {
456
+ id: String(tx.id),
457
+ providerId: PAYSTACK,
458
+ reference,
459
+ amount,
460
+ fees,
461
+ netAmount: net,
462
+ status,
463
+ customer,
464
+ authorizationUrl: void 0,
465
+ accessCode: void 0,
466
+ channel: tx.channel,
467
+ attempts: Object.freeze(attempts),
468
+ metadata: tx.metadata ? Object.freeze({ ...tx.metadata }) : emptyMetadata(),
469
+ createdAt: requireTimestamp([tx.created_at], "a transaction"),
470
+ updatedAt: requireTimestamp([tx.updated_at, tx.created_at], "a transaction"),
471
+ paidAt: tx.paid_at ? toPaystackDate(tx.paid_at) : void 0,
472
+ failureReason: tx.status === "failed" ? tx.gateway_response : void 0
473
+ };
474
+ }
475
+ function mapInitializeResponse(response, request) {
476
+ if (!response.status) {
477
+ throw new ProviderError(response.message, {
478
+ provider: PAYSTACK,
479
+ httpStatus: 422,
480
+ isRetryable: false
481
+ });
482
+ }
483
+ const data = response.data;
484
+ const reference = request.reference;
485
+ const amount = request.amount;
486
+ return {
487
+ providerId: PAYSTACK,
488
+ reference,
489
+ amount,
490
+ status: { kind: "initialized" },
491
+ customer: request.customer.kind === "inline" ? request.customer.customer : {
492
+ id: "pending",
493
+ email: request.customer.kind === "new" ? request.customer.email : "unknown",
494
+ phone: request.customer.kind === "new" ? request.customer.phone : void 0,
495
+ name: request.customer.kind === "new" ? request.customer.name : void 0
496
+ },
497
+ authorizationUrl: data.authorization_url,
498
+ accessCode: data.access_code,
499
+ channel: void 0,
500
+ attempts: Object.freeze([]),
501
+ metadata: request.metadata ? Object.freeze({ ...request.metadata }) : emptyMetadata(),
502
+ createdAt: /* @__PURE__ */ new Date(),
503
+ updatedAt: /* @__PURE__ */ new Date()
504
+ };
505
+ }
506
+ function mapPaystackResponseToPayment(response) {
507
+ if (!response.status) {
508
+ throw new VerificationError(`Paystack verification failed: ${response.message}`, {
509
+ provider: PAYSTACK
510
+ });
511
+ }
512
+ return mapPaystackTransactionToPayment(response.data);
513
+ }
514
+ function mapPaystackListResponse(response) {
515
+ if (!response.status) {
516
+ throw new ProviderError(response.message, {
517
+ provider: PAYSTACK,
518
+ httpStatus: 422,
519
+ isRetryable: false
520
+ });
521
+ }
522
+ return {
523
+ items: response.data.map(mapPaystackTransactionToPayment),
524
+ total: response.meta.total,
525
+ page: response.meta.page,
526
+ perPage: response.meta.perPage
527
+ };
528
+ }
529
+ function mapPaystackWebhookEvent(webhook, rawBody, receivedAt) {
530
+ const data = webhook.data ?? {};
531
+ const resourceId = typeof data.id === "number" && Number.isFinite(data.id) ? String(data.id) : void 0;
532
+ return {
533
+ id: resourceId ?? contentHash(rawBody),
534
+ provider: PAYSTACK,
535
+ type: normalizeWebhookType(webhook.event),
536
+ originalType: webhook.event,
537
+ createdAt: toPaystackDate(data.created_at, data.createdAt) ?? receivedAt,
538
+ receivedAt,
539
+ payload: data,
540
+ raw: webhook
541
+ };
542
+ }
543
+ function contentHash(rawBody) {
544
+ return `sha256:${createHash("sha256").update(rawBody, "utf8").digest("hex").slice(0, 32)}`;
545
+ }
546
+ function normalizeWebhookType(event) {
547
+ switch (event) {
548
+ case "charge.success":
549
+ return "payment.succeeded";
550
+ case "charge.failed":
551
+ case "charge.timeout":
552
+ return "payment.failed";
553
+ case "charge.pending":
554
+ case "charge.ongoing":
555
+ return "payment.pending";
556
+ case "charge.created":
557
+ return "payment.initialized";
558
+ case "refund.processed":
559
+ return "refund.succeeded";
560
+ case "refund.failed":
561
+ return "refund.failed";
562
+ case "refund.pending":
563
+ case "refund.processing":
564
+ return "refund.initiated";
565
+ case "transfer.success":
566
+ return "transfer.succeeded";
567
+ case "transfer.failed":
568
+ return "transfer.failed";
569
+ case "transfer.reversed":
570
+ return "transfer.reversed";
571
+ default:
572
+ return "payment.unknown";
573
+ }
574
+ }
575
+ function mapPaystackRefundResponse(response, now) {
576
+ if (!response.status) {
577
+ throw new ProviderError(response.message, {
578
+ provider: PAYSTACK,
579
+ httpStatus: 422,
580
+ isRetryable: false
581
+ });
582
+ }
583
+ const data = response.data;
584
+ const paymentId = transactionIdOf(data.transaction);
585
+ const settled = data.status === "processed" || data.status === "success";
586
+ const providerStatus = isNeedsAttention(data.status) ? data.status : void 0;
587
+ return {
588
+ id: String(data.id),
589
+ // Only reachable on a response that omits `transaction` entirely, which
590
+ // neither documented refund shape does.
591
+ paymentId: paymentId ?? "unknown",
592
+ amount: Money({ amount: data.amount, currency: data.currency }),
593
+ status: mapRefundStatus(data.status),
594
+ ...providerStatus ? { providerStatus } : {},
595
+ reason: data.merchant_note ?? "",
596
+ reference: String(data.id),
597
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
598
+ completedAt: settled ? toPaystackDate(data.updatedAt, data.updated_at) : void 0
599
+ };
600
+ }
601
+ function isNeedsAttention(status) {
602
+ const normalized = status.toLowerCase();
603
+ return normalized === "needs-attention" || normalized === "needs_attention";
604
+ }
605
+ function mapRefundStatus(status) {
606
+ switch (status.toLowerCase()) {
607
+ case "processed":
608
+ case "success":
609
+ case "succeeded":
610
+ return "succeeded";
611
+ case "failed":
612
+ case "cancelled":
613
+ return "failed";
614
+ case "pending":
615
+ case "processing":
616
+ case "needs-attention":
617
+ return "pending";
618
+ default:
619
+ return "pending";
620
+ }
621
+ }
622
+ var HmacWebhookVerifier = class {
623
+ secret;
624
+ algorithm;
625
+ constructor(secret, algorithm = "sha512") {
626
+ this.secret = secret;
627
+ this.algorithm = algorithm;
628
+ }
629
+ verify(rawBody, signature) {
630
+ try {
631
+ const bodyBuffer = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
632
+ const expected = createHmac(this.algorithm, this.secret).update(bodyBuffer).digest("hex");
633
+ const a = Buffer.from(expected);
634
+ const b = Buffer.from(signature);
635
+ if (a.length !== b.length) {
636
+ return false;
637
+ }
638
+ return timingSafeEqual(a, b);
639
+ } catch {
640
+ return false;
641
+ }
642
+ }
643
+ };
644
+
645
+ // src/infrastructure/providers/paystack/paystack-webhook.ts
646
+ var SIGNATURE_HEADER = "x-paystack-signature";
647
+ function parsePaystackWebhook(headers, rawBody, webhookSecret, now, signatureFallback) {
648
+ const signature = findHeader(headers, SIGNATURE_HEADER) ?? signatureFallback;
649
+ if (!signature) {
650
+ return err(new WebhookValidationError("Missing x-paystack-signature header"));
651
+ }
652
+ const verifier = new HmacWebhookVerifier(webhookSecret, "sha512");
653
+ if (!verifier.verify(rawBody, signature)) {
654
+ return err(new WebhookValidationError("Invalid webhook signature"));
655
+ }
656
+ let payload;
657
+ try {
658
+ payload = JSON.parse(rawBody);
659
+ } catch {
660
+ return err(new WebhookValidationError("Invalid webhook body: not valid JSON"));
661
+ }
662
+ if (!payload.event || !payload.data) {
663
+ return err(new WebhookValidationError("Invalid webhook body: missing event or data"));
664
+ }
665
+ try {
666
+ const event = mapPaystackWebhookEvent(payload, rawBody, now);
667
+ return ok(event);
668
+ } catch (e) {
669
+ return err(new WebhookValidationError(
670
+ `Failed to parse webhook payload: ${e instanceof Error ? e.message : String(e)}`
671
+ ));
672
+ }
673
+ }
674
+ function findHeader(headers, name) {
675
+ const lower = name.toLowerCase();
676
+ for (const key of Object.keys(headers)) {
677
+ if (key.toLowerCase() === lower) {
678
+ return headers[key];
679
+ }
680
+ }
681
+ return void 0;
682
+ }
683
+
684
+ // src/infrastructure/providers/paystack/paystack-transfer-mapper.ts
685
+ var PAYSTACK2 = Provider("paystack");
686
+ function emptyMetadata2() {
687
+ return Object.freeze({});
688
+ }
689
+ function assertOk(response) {
690
+ if (response.status) return;
691
+ throw new ProviderError(response.message, {
692
+ provider: PAYSTACK2,
693
+ httpStatus: 422,
694
+ isRetryable: false
695
+ });
696
+ }
697
+ function mapPaystackBank(bank) {
698
+ return {
699
+ code: bank.code,
700
+ name: bank.name,
701
+ currency: Currency(bank.currency)
702
+ };
703
+ }
704
+ function mapPaystackBankListResponse(response) {
705
+ assertOk(response);
706
+ return response.data.filter((bank) => bank.active !== false).map(mapPaystackBank);
707
+ }
708
+ function mapPaystackRecipient(data, now) {
709
+ return {
710
+ code: data.recipient_code,
711
+ name: data.name,
712
+ accountNumber: data.details.account_number,
713
+ bankCode: data.details.bank_code,
714
+ currency: Currency(data.currency),
715
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
716
+ metadata: data.metadata ? Object.freeze({ ...data.metadata }) : emptyMetadata2()
717
+ };
718
+ }
719
+ function mapPaystackCreateRecipientResponse(response, now) {
720
+ assertOk(response);
721
+ return mapPaystackRecipient(response.data, now);
722
+ }
723
+ function stubRecipient(recipientId, currency, now) {
724
+ return {
725
+ code: recipientId === null ? "unknown" : String(recipientId),
726
+ name: "unknown",
727
+ accountNumber: "unknown",
728
+ bankCode: "unknown",
729
+ currency: Currency(currency),
730
+ createdAt: now,
731
+ metadata: emptyMetadata2()
732
+ };
733
+ }
734
+ function resolveTransferRecipient(value, currency, now, hint) {
735
+ if (value !== null && value !== void 0 && typeof value === "object") {
736
+ return mapPaystackRecipient(value, now);
737
+ }
738
+ if (hint) return hint;
739
+ return stubRecipient(typeof value === "number" ? value : null, currency, now);
740
+ }
741
+ function mapPaystackTransferStatus(status, data, now) {
742
+ const updatedAt = toPaystackDate(data.updatedAt, data.updated_at, data.createdAt, data.created_at);
743
+ switch (status) {
744
+ case "pending":
745
+ return { kind: "pending" };
746
+ // Paystack requires an OTP to be finalized when it reports `otp`; without
747
+ // the flag a caller cannot tell "queued" from "waiting on you".
748
+ case "otp":
749
+ return { kind: "pending", requiresAction: true };
750
+ case "processing":
751
+ return { kind: "processing" };
752
+ case "success":
753
+ return {
754
+ kind: "succeeded",
755
+ settledAt: toPaystackDate(
756
+ data.transferred_at,
757
+ data.updatedAt,
758
+ data.updated_at,
759
+ data.createdAt,
760
+ data.created_at
761
+ ) ?? now
762
+ };
763
+ case "failed":
764
+ return {
765
+ kind: "failed",
766
+ reason: data.reason || "transfer_failed",
767
+ failedAt: updatedAt ?? now
768
+ };
769
+ case "reversed":
770
+ return { kind: "reversed", reversedAt: updatedAt ?? now };
771
+ default:
772
+ return { kind: "pending" };
773
+ }
774
+ }
775
+ function mapFee(data, currency) {
776
+ const charged = data.fee_charged;
777
+ if (typeof charged !== "number" || !Number.isInteger(charged) || charged < 0) {
778
+ return void 0;
779
+ }
780
+ return Money({ amount: charged, currency });
781
+ }
782
+ function mapPaystackTransferToDomain(data, now, recipientHint) {
783
+ const currency = Currency(data.currency);
784
+ const fee = mapFee(data, currency);
785
+ return {
786
+ id: String(data.id),
787
+ providerId: PAYSTACK2,
788
+ amount: Money({ amount: data.amount, currency }),
789
+ ...fee ? { fee } : {},
790
+ recipient: resolveTransferRecipient(data.recipient, data.currency, now, recipientHint),
791
+ status: mapPaystackTransferStatus(data.status, data, now),
792
+ reference: data.reference,
793
+ reason: data.reason || void 0,
794
+ transferCode: data.transfer_code,
795
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
796
+ completedAt: toPaystackDate(data.transferred_at),
797
+ failureReason: data.status === "failed" ? data.reason || void 0 : void 0,
798
+ metadata: emptyMetadata2()
799
+ };
800
+ }
801
+ function mapPaystackTransferResponse(response, now, recipientHint) {
802
+ assertOk(response);
803
+ return mapPaystackTransferToDomain(response.data, now, recipientHint);
804
+ }
805
+ function mapPaystackTransferListResponse(response, now) {
806
+ assertOk(response);
807
+ return {
808
+ items: response.data.map((data) => mapPaystackTransferToDomain(data, now)),
809
+ total: response.meta.total,
810
+ page: response.meta.page,
811
+ perPage: response.meta.perPage
812
+ };
813
+ }
814
+
815
+ // src/infrastructure/providers/paystack/paystack-adapter.ts
816
+ var PAYSTACK_BASE_URL = "https://api.paystack.co";
817
+ var PAYSTACK_BANK_TYPES_BY_CURRENCY = {
818
+ NGN: "nuban",
819
+ USD: "nuban",
820
+ GHS: "ghipss",
821
+ ZAR: "basa"
822
+ };
823
+ var PAYSTACK_TRANSFER_REFERENCE_RE = /^[a-z0-9_-]{16,50}$/;
824
+ var BANK_PAGE_SIZE = 100;
825
+ var MAX_BANK_PAGES = 10;
826
+ var PAYSTACK_CAPABILITIES = {
827
+ supportsAuthorizationUrl: true,
828
+ supportsRecurring: true,
829
+ supportsPartialRefund: true,
830
+ supportsWebhooks: true,
831
+ supportsTransfers: true,
832
+ // Paystack documents no Idempotency-Key header: dedupe relies on unique
833
+ // references, and a retried refund can duplicate the effect.
834
+ supportsIdempotencyKey: false,
835
+ supportedCurrencies: [
836
+ "NGN",
837
+ "GHS",
838
+ "ZAR",
839
+ "KES",
840
+ "USD"
841
+ ],
842
+ supportedChannels: ["card", "bank", "ussd", "qr", "mobile_money", "bank_transfer"],
843
+ supportedTransferCurrencies: [
844
+ "NGN",
845
+ "GHS",
846
+ "ZAR",
847
+ "KES"
848
+ ]
849
+ };
850
+ var PaystackAdapter = class {
851
+ id;
852
+ capabilities;
853
+ httpClient;
854
+ logger;
855
+ clock;
856
+ eventBus;
857
+ idGenerator;
858
+ webhookVerifier;
859
+ secretKey;
860
+ webhookSecret;
861
+ baseUrl;
862
+ timeoutMs;
863
+ constructor(config, deps) {
864
+ this.id = "paystack";
865
+ this.capabilities = PAYSTACK_CAPABILITIES;
866
+ this.httpClient = deps.httpClient;
867
+ this.logger = deps.logger;
868
+ this.clock = deps.clock;
869
+ this.eventBus = deps.eventBus;
870
+ this.idGenerator = deps.idGenerator;
871
+ this.webhookVerifier = deps.webhookVerifier;
872
+ this.secretKey = config.secretKey;
873
+ this.webhookSecret = config.webhookSecret ?? config.secretKey;
874
+ this.baseUrl = config.baseUrl ?? PAYSTACK_BASE_URL;
875
+ this.timeoutMs = config.timeoutMs ?? 3e4;
876
+ }
877
+ async initialize(req) {
878
+ if (req.products && req.products.length > 0) {
879
+ return err(
880
+ new UnsupportedProviderError(
881
+ "Paystack does not support catalog checkouts; product-based checkouts need a provider with the subscription capability (Bachs)",
882
+ { provider: this.id }
883
+ )
884
+ );
885
+ }
886
+ if (req.customer.kind === "existing") {
887
+ return err(
888
+ new ValidationError(
889
+ 'Paystack cannot initialize from an existing customer id because the API requires an email; pass { kind: "new", email } or { kind: "inline", customer }'
890
+ )
891
+ );
892
+ }
893
+ const amount = req.amount;
894
+ if (!amount) {
895
+ throw new ValidationError("Paystack initialize requires an amount");
896
+ }
897
+ const payload = {
898
+ amount: amount.amount,
899
+ email: getEmail(req.customer),
900
+ reference: req.reference,
901
+ currency: amount.currency,
902
+ callback_url: req.callbackUrl,
903
+ channels: req.channels ? req.channels.slice() : void 0,
904
+ metadata: req.metadata ? req.metadata : void 0
905
+ };
906
+ const correlationId = req.correlationId ?? this.idGenerator.generate();
907
+ this.logger.info("initializing payment", {
908
+ provider: "paystack",
909
+ reference: req.reference,
910
+ correlationId,
911
+ amount: String(amount.amount),
912
+ currency: amount.currency
913
+ });
914
+ const result = await this.httpClient.send({
915
+ method: "POST",
916
+ url: `${this.baseUrl}/transaction/initialize`,
917
+ headers: this.authHeaders(),
918
+ body: JSON.stringify(payload),
919
+ timeoutMs: this.timeoutMs,
920
+ correlationId,
921
+ idempotencyKey: req.idempotencyKey
922
+ });
923
+ if (!result.ok) {
924
+ this.logger.error("initialize failed", result.error, {
925
+ provider: "paystack",
926
+ reference: req.reference,
927
+ correlationId
928
+ });
929
+ return result;
930
+ }
931
+ try {
932
+ const response = JSON.parse(result.value.body);
933
+ const payment = mapInitializeResponse(response, req);
934
+ return ok(payment);
935
+ } catch (e) {
936
+ return err(mapMapperError(e, { provider: this.id, context: "initialize response" }));
937
+ }
938
+ }
939
+ async verify(reference) {
940
+ const correlationId = this.idGenerator.generate();
941
+ this.logger.info("verifying payment", {
942
+ provider: "paystack",
943
+ reference,
944
+ correlationId
945
+ });
946
+ const result = await this.httpClient.send({
947
+ method: "GET",
948
+ url: `${this.baseUrl}/transaction/verify/${encodeURIComponent(reference)}`,
949
+ headers: this.authHeaders(),
950
+ timeoutMs: this.timeoutMs,
951
+ correlationId
952
+ });
953
+ if (!result.ok) return result;
954
+ try {
955
+ const response = JSON.parse(result.value.body);
956
+ const payment = mapPaystackResponseToPayment(response);
957
+ return ok(payment);
958
+ } catch (e) {
959
+ return err(mapMapperError(e, { provider: this.id, context: "verify response" }));
960
+ }
961
+ }
962
+ async fetch(id) {
963
+ const correlationId = this.idGenerator.generate();
964
+ this.logger.info("fetching payment", {
965
+ provider: "paystack",
966
+ paymentId: id,
967
+ correlationId
968
+ });
969
+ const result = await this.httpClient.send({
970
+ method: "GET",
971
+ url: `${this.baseUrl}/transaction/${encodeURIComponent(id)}`,
972
+ headers: this.authHeaders(),
973
+ timeoutMs: this.timeoutMs,
974
+ correlationId
975
+ });
976
+ if (!result.ok) return result;
977
+ try {
978
+ const response = JSON.parse(result.value.body);
979
+ const payment = mapPaystackResponseToPayment(response);
980
+ return ok(payment);
981
+ } catch (e) {
982
+ return err(mapMapperError(e, { provider: this.id, context: "fetch response" }));
983
+ }
984
+ }
985
+ async list(query = {}) {
986
+ const correlationId = this.idGenerator.generate();
987
+ const params = new URLSearchParams();
988
+ if (query.perPage) params.set("perPage", String(query.perPage));
989
+ if (query.page) params.set("page", String(query.page));
990
+ if (query.from) params.set("from", query.from.toISOString());
991
+ if (query.to) params.set("to", query.to.toISOString());
992
+ if (query.status) params.set("status", query.status);
993
+ if (query.customer) params.set("customer", query.customer);
994
+ const queryStr = params.toString();
995
+ const url = `${this.baseUrl}/transaction${queryStr ? `?${queryStr}` : ""}`;
996
+ this.logger.info("listing payments", {
997
+ provider: "paystack",
998
+ correlationId,
999
+ query: queryStr
1000
+ });
1001
+ const result = await this.httpClient.send({
1002
+ method: "GET",
1003
+ url,
1004
+ headers: this.authHeaders(),
1005
+ timeoutMs: this.timeoutMs,
1006
+ correlationId
1007
+ });
1008
+ if (!result.ok) return result;
1009
+ try {
1010
+ const response = JSON.parse(result.value.body);
1011
+ const page = mapPaystackListResponse(response);
1012
+ return ok(page);
1013
+ } catch (e) {
1014
+ return err(mapMapperError(e, { provider: this.id, context: "list response" }));
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Paystack has no `currency` on the refund object but accepts one on the
1019
+ * request, so the currency of the caller's `Money` is forwarded rather than
1020
+ * silently reinterpreted in the charge currency.
1021
+ */
1022
+ async refund(input) {
1023
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
1024
+ const body = JSON.stringify({
1025
+ transaction: input.paymentId,
1026
+ amount: input.amount?.amount,
1027
+ currency: input.amount?.currency,
1028
+ merchant_note: input.reason
1029
+ });
1030
+ this.logger.info("refunding payment", {
1031
+ provider: "paystack",
1032
+ paymentId: input.paymentId,
1033
+ correlationId
1034
+ });
1035
+ const result = await this.httpClient.send({
1036
+ method: "POST",
1037
+ url: `${this.baseUrl}/refund`,
1038
+ headers: this.authHeaders(),
1039
+ body,
1040
+ timeoutMs: this.timeoutMs,
1041
+ correlationId,
1042
+ idempotencyKey: input.idempotencyKey
1043
+ });
1044
+ if (!result.ok) return result;
1045
+ try {
1046
+ const response = JSON.parse(result.value.body);
1047
+ const refund = mapPaystackRefundResponse(response, this.clock.now());
1048
+ return ok(refund);
1049
+ } catch (e) {
1050
+ return err(mapMapperError(e, { provider: this.id, context: "refund response" }));
1051
+ }
1052
+ }
1053
+ async parseWebhook(headers, rawBody, signature) {
1054
+ return parsePaystackWebhook(
1055
+ headers,
1056
+ rawBody,
1057
+ this.webhookSecret,
1058
+ this.clock.now(),
1059
+ signature
1060
+ );
1061
+ }
1062
+ async fetchRefund(refundId) {
1063
+ const correlationId = this.idGenerator.generate();
1064
+ this.logger.info("fetching refund", {
1065
+ provider: "paystack",
1066
+ refundId,
1067
+ correlationId
1068
+ });
1069
+ const result = await this.httpClient.send({
1070
+ method: "GET",
1071
+ url: `${this.baseUrl}/refund/${encodeURIComponent(refundId)}`,
1072
+ headers: this.authHeaders(),
1073
+ timeoutMs: this.timeoutMs,
1074
+ correlationId
1075
+ });
1076
+ if (!result.ok) return result;
1077
+ try {
1078
+ const response = JSON.parse(result.value.body);
1079
+ const refund = mapPaystackRefundResponse(response, this.clock.now());
1080
+ return ok(refund);
1081
+ } catch (e) {
1082
+ return err(mapMapperError(e, { provider: this.id, context: "fetch refund response" }));
1083
+ }
1084
+ }
1085
+ /**
1086
+ * `GET /bank` paginates by cursor and caps `perPage` at 100, so a single
1087
+ * request silently drops the rest of the list. Follow `meta.next` until the
1088
+ * provider stops offering one, with a defensive page ceiling.
1089
+ */
1090
+ async listBankCodes(input) {
1091
+ const correlationId = this.idGenerator.generate();
1092
+ this.logger.info("listing bank codes", {
1093
+ provider: this.id,
1094
+ currency: input.currency,
1095
+ correlationId
1096
+ });
1097
+ const banks = [];
1098
+ let cursor;
1099
+ let truncated = false;
1100
+ for (let page = 1; page <= MAX_BANK_PAGES; page++) {
1101
+ const params = new URLSearchParams({
1102
+ currency: input.currency,
1103
+ perPage: String(BANK_PAGE_SIZE),
1104
+ use_cursor: "true"
1105
+ });
1106
+ if (cursor) params.set("next", cursor);
1107
+ const result = await this.httpClient.send({
1108
+ method: "GET",
1109
+ url: `${this.baseUrl}/bank?${params.toString()}`,
1110
+ headers: this.authHeaders(),
1111
+ timeoutMs: this.timeoutMs,
1112
+ correlationId
1113
+ });
1114
+ if (!result.ok) return result;
1115
+ let next;
1116
+ try {
1117
+ const response = JSON.parse(result.value.body);
1118
+ banks.push(...mapPaystackBankListResponse(response));
1119
+ next = response.meta?.next ?? void 0;
1120
+ } catch (e) {
1121
+ return err(mapMapperError(e, { provider: this.id, context: "bank list response" }));
1122
+ }
1123
+ if (!next) break;
1124
+ cursor = next;
1125
+ if (page === MAX_BANK_PAGES) truncated = true;
1126
+ }
1127
+ if (truncated) {
1128
+ this.logger.warn("bank list truncated", {
1129
+ provider: this.id,
1130
+ currency: input.currency,
1131
+ pages: MAX_BANK_PAGES,
1132
+ correlationId
1133
+ });
1134
+ }
1135
+ return ok(Object.freeze(banks));
1136
+ }
1137
+ async resolveAccount(input) {
1138
+ const correlationId = this.idGenerator.generate();
1139
+ const params = new URLSearchParams({
1140
+ account_number: input.accountNumber,
1141
+ bank_code: input.bankCode
1142
+ });
1143
+ this.logger.info("resolving account", {
1144
+ provider: this.id,
1145
+ bankCode: input.bankCode,
1146
+ correlationId
1147
+ });
1148
+ const result = await this.httpClient.send({
1149
+ method: "GET",
1150
+ url: `${this.baseUrl}/bank/resolve?${params.toString()}`,
1151
+ headers: this.authHeaders(),
1152
+ timeoutMs: this.timeoutMs,
1153
+ correlationId
1154
+ });
1155
+ if (!result.ok) return result;
1156
+ try {
1157
+ const response = JSON.parse(result.value.body);
1158
+ if (!response.status) {
1159
+ return err(new ProviderError(response.message, {
1160
+ provider: this.id,
1161
+ httpStatus: 422,
1162
+ isRetryable: false
1163
+ }));
1164
+ }
1165
+ return ok({
1166
+ accountName: response.data.account_name,
1167
+ accountNumber: response.data.account_number,
1168
+ bankId: response.data.bank_id
1169
+ });
1170
+ } catch (e) {
1171
+ return err(mapMapperError(e, { provider: this.id, context: "resolve account response" }));
1172
+ }
1173
+ }
1174
+ async createRecipient(input) {
1175
+ const correlationId = this.idGenerator.generate();
1176
+ const type = resolveRecipientType(input);
1177
+ const body = {
1178
+ type,
1179
+ name: input.name,
1180
+ account_number: input.accountNumber,
1181
+ bank_code: input.bankCode,
1182
+ currency: input.currency,
1183
+ metadata: input.metadata ? input.metadata : void 0
1184
+ };
1185
+ this.logger.info("creating transfer recipient", {
1186
+ provider: this.id,
1187
+ bankCode: input.bankCode,
1188
+ type,
1189
+ correlationId
1190
+ });
1191
+ const result = await this.httpClient.send({
1192
+ method: "POST",
1193
+ url: `${this.baseUrl}/transferrecipient`,
1194
+ headers: this.authHeaders(),
1195
+ body: JSON.stringify(body),
1196
+ timeoutMs: this.timeoutMs,
1197
+ correlationId
1198
+ });
1199
+ if (!result.ok) return result;
1200
+ try {
1201
+ const response = JSON.parse(result.value.body);
1202
+ const recipient = mapPaystackCreateRecipientResponse(response, this.clock.now());
1203
+ return ok(recipient);
1204
+ } catch (e) {
1205
+ return err(mapMapperError(e, { provider: this.id, context: "create recipient response" }));
1206
+ }
1207
+ }
1208
+ async initiateTransfer(input) {
1209
+ if (input.quoteId) {
1210
+ return err(
1211
+ new UnsupportedProviderError(
1212
+ "Paystack payouts are always in the transfer currency; quoteId is only supported by providers with cross-currency payouts (Bachs)",
1213
+ { provider: this.id }
1214
+ )
1215
+ );
1216
+ }
1217
+ const amount = input.amount;
1218
+ if (!amount) {
1219
+ throw new ValidationError(
1220
+ "Paystack payouts require an amount: pass amount, or a quoteId for a provider that supports cross-currency payouts"
1221
+ );
1222
+ }
1223
+ if (input.currency !== amount.currency) {
1224
+ throw new ValidationError(
1225
+ `Transfer currency ${input.currency} does not match amount currency ${amount.currency}`
1226
+ );
1227
+ }
1228
+ assertTransferReference(input.reference);
1229
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
1230
+ const body = {
1231
+ source: "balance",
1232
+ amount: amount.amount,
1233
+ recipient: input.recipientCode,
1234
+ reference: input.reference,
1235
+ reason: input.reason,
1236
+ currency: input.currency,
1237
+ account_reference: input.accountReference
1238
+ };
1239
+ this.logger.info("initiating transfer", {
1240
+ provider: this.id,
1241
+ reference: input.reference,
1242
+ correlationId
1243
+ });
1244
+ const result = await this.httpClient.send({
1245
+ method: "POST",
1246
+ url: `${this.baseUrl}/transfer`,
1247
+ headers: this.authHeaders(),
1248
+ body: JSON.stringify(body),
1249
+ timeoutMs: this.timeoutMs,
1250
+ correlationId,
1251
+ idempotencyKey: input.idempotencyKey
1252
+ });
1253
+ if (!result.ok) return result;
1254
+ try {
1255
+ const response = JSON.parse(result.value.body);
1256
+ const now = this.clock.now();
1257
+ const recipient = await this.lookupRecipient(input.recipientCode, now);
1258
+ if (!recipient) {
1259
+ this.logger.warn("transfer recipient could not be resolved; returning a code-only stub", {
1260
+ provider: this.id,
1261
+ recipientCode: input.recipientCode,
1262
+ correlationId
1263
+ });
1264
+ }
1265
+ const transfer = mapPaystackTransferResponse(response, now, recipient);
1266
+ return ok(transfer);
1267
+ } catch (e) {
1268
+ return err(mapMapperError(e, { provider: this.id, context: "initiate transfer response" }));
1269
+ }
1270
+ }
1271
+ async fetchTransfer(id) {
1272
+ const correlationId = this.idGenerator.generate();
1273
+ this.logger.info("fetching transfer", {
1274
+ provider: this.id,
1275
+ transferId: id,
1276
+ correlationId
1277
+ });
1278
+ const result = await this.httpClient.send({
1279
+ method: "GET",
1280
+ url: `${this.baseUrl}/transfer/${encodeURIComponent(id)}`,
1281
+ headers: this.authHeaders(),
1282
+ timeoutMs: this.timeoutMs,
1283
+ correlationId
1284
+ });
1285
+ if (!result.ok) return result;
1286
+ try {
1287
+ const response = JSON.parse(result.value.body);
1288
+ return ok(mapPaystackTransferResponse(response, this.clock.now()));
1289
+ } catch (e) {
1290
+ return err(mapMapperError(e, { provider: this.id, context: "fetch transfer response" }));
1291
+ }
1292
+ }
1293
+ async listTransfers(query = {}) {
1294
+ const correlationId = this.idGenerator.generate();
1295
+ const params = new URLSearchParams();
1296
+ if (query.perPage) params.set("perPage", String(query.perPage));
1297
+ if (query.page) params.set("page", String(query.page));
1298
+ if (query.from) params.set("from", query.from.toISOString());
1299
+ if (query.to) params.set("to", query.to.toISOString());
1300
+ const queryStr = params.toString();
1301
+ const url = `${this.baseUrl}/transfer${queryStr ? `?${queryStr}` : ""}`;
1302
+ this.logger.info("listing transfers", {
1303
+ provider: this.id,
1304
+ correlationId,
1305
+ query: queryStr
1306
+ });
1307
+ const result = await this.httpClient.send({
1308
+ method: "GET",
1309
+ url,
1310
+ headers: this.authHeaders(),
1311
+ timeoutMs: this.timeoutMs,
1312
+ correlationId
1313
+ });
1314
+ if (!result.ok) return result;
1315
+ try {
1316
+ const response = JSON.parse(result.value.body);
1317
+ return ok(mapPaystackTransferListResponse(response, this.clock.now()));
1318
+ } catch (e) {
1319
+ return err(mapMapperError(e, { provider: this.id, context: "list transfers response" }));
1320
+ }
1321
+ }
1322
+ async health() {
1323
+ const start = Date.now();
1324
+ try {
1325
+ const result = await this.httpClient.send({
1326
+ method: "GET",
1327
+ url: `${this.baseUrl}/transaction`,
1328
+ headers: this.authHeaders(),
1329
+ timeoutMs: 5e3
1330
+ });
1331
+ if (!result.ok) {
1332
+ this.logger.warn("health check failed", {
1333
+ provider: this.id,
1334
+ code: result.error.code,
1335
+ httpStatus: result.error.httpStatus,
1336
+ message: result.error.message
1337
+ });
1338
+ }
1339
+ return {
1340
+ healthy: result.ok,
1341
+ latencyMs: Date.now() - start,
1342
+ timestamp: this.clock.now()
1343
+ };
1344
+ } catch (error) {
1345
+ this.logger.warn("health check threw", {
1346
+ provider: this.id,
1347
+ message: error instanceof Error ? error.message : String(error)
1348
+ });
1349
+ return {
1350
+ healthy: false,
1351
+ latencyMs: Date.now() - start,
1352
+ timestamp: this.clock.now()
1353
+ };
1354
+ }
1355
+ }
1356
+ /** Best-effort recipient lookup; a failure must never fail the transfer. */
1357
+ async lookupRecipient(code, now) {
1358
+ const result = await this.httpClient.send({
1359
+ method: "GET",
1360
+ url: `${this.baseUrl}/transferrecipient/${encodeURIComponent(code)}`,
1361
+ headers: this.authHeaders(),
1362
+ timeoutMs: this.timeoutMs
1363
+ });
1364
+ if (!result.ok) return void 0;
1365
+ try {
1366
+ const response = JSON.parse(result.value.body);
1367
+ if (!response.status) return void 0;
1368
+ return mapPaystackRecipient(response.data, now);
1369
+ } catch {
1370
+ return void 0;
1371
+ }
1372
+ }
1373
+ authHeaders() {
1374
+ return {
1375
+ Authorization: `Bearer ${this.secretKey}`
1376
+ };
1377
+ }
1378
+ };
1379
+ function getEmail(cr) {
1380
+ switch (cr.kind) {
1381
+ case "inline":
1382
+ return cr.customer.email;
1383
+ case "new":
1384
+ return cr.email;
1385
+ case "existing":
1386
+ return "";
1387
+ }
1388
+ }
1389
+ function resolveRecipientType(input) {
1390
+ if (input.type === "mobile_money") return "mobile_money";
1391
+ const type = PAYSTACK_BANK_TYPES_BY_CURRENCY[input.currency];
1392
+ if (!type) {
1393
+ throw new ValidationError(
1394
+ `Paystack has no bank recipient type for ${input.currency}; pass type: "mobile_money" for a wallet destination, or use one of ${Object.keys(PAYSTACK_BANK_TYPES_BY_CURRENCY).join(", ")}`
1395
+ );
1396
+ }
1397
+ return type;
1398
+ }
1399
+ function assertTransferReference(reference) {
1400
+ if (!PAYSTACK_TRANSFER_REFERENCE_RE.test(reference)) {
1401
+ throw new ValidationError(
1402
+ 'Paystack transfer references must be 16-50 characters of lowercase letters, digits, "-" or "_" (for example "payout_2026_10_17_0012")'
1403
+ );
1404
+ }
1405
+ }
1406
+
1407
+ // src/infrastructure/providers/paystack/register.ts
1408
+ var PAYSTACK_ID = "paystack";
1409
+ registerProvider(PAYSTACK_ID, (config, deps) => new PaystackAdapter(config, deps));
1410
+
1411
+ // src/infrastructure/providers/bachs/bachs-connection.ts
1412
+ var BACHS_LIVE_BASE_URL = "https://api.bachs.io";
1413
+ var BACHS_SANDBOX_BASE_URL = "https://sandbox-api.bachs.io";
1414
+ var DEFAULT_TIMEOUT_MS = 3e4;
1415
+ function createBachsConnection(config) {
1416
+ const baseUrl = config.baseUrl ?? (config.secretKey.startsWith("sk_sandbox_") ? BACHS_SANDBOX_BASE_URL : BACHS_LIVE_BASE_URL);
1417
+ return {
1418
+ baseUrl,
1419
+ secretKey: config.secretKey,
1420
+ webhookSecret: config.webhookSecret ?? "",
1421
+ webhookToleranceSeconds: readTolerance(config.options),
1422
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1423
+ environment: baseUrl === BACHS_SANDBOX_BASE_URL ? "sandbox" : "live"
1424
+ };
1425
+ }
1426
+ function readTolerance(options) {
1427
+ const value = options?.["webhookToleranceSeconds"];
1428
+ return typeof value === "number" ? value : void 0;
1429
+ }
1430
+
1431
+ // src/infrastructure/providers/bachs/bachs-pagination.ts
1432
+ var DEFAULT_PAGE_SIZE = 50;
1433
+ var MAX_PAGE_SIZE = 100;
1434
+ function resolveBachsPagination(query) {
1435
+ const requested = query.perPage ?? DEFAULT_PAGE_SIZE;
1436
+ const limit = Math.min(
1437
+ Math.max(Number.isFinite(requested) ? Math.trunc(requested) : DEFAULT_PAGE_SIZE, 1),
1438
+ MAX_PAGE_SIZE
1439
+ );
1440
+ const offset = query.cursor ? 0 : Math.max((query.page ?? 1) - 1, 0) * limit;
1441
+ return { limit, offset, clamped: limit !== requested };
1442
+ }
1443
+
1444
+ // src/domain/product/recurring-cadence.ts
1445
+ var INTERVALS = /* @__PURE__ */ new Set(["day", "week", "month", "year"]);
1446
+ function RecurringCadence(input) {
1447
+ if (!INTERVALS.has(input.interval)) {
1448
+ throw new ValidationError(
1449
+ `Invalid billing interval "${input.interval}": must be day, week, month, or year`
1450
+ );
1451
+ }
1452
+ if (!Number.isInteger(input.frequency) || input.frequency < 1) {
1453
+ throw new ValidationError(
1454
+ `Invalid billing frequency "${input.frequency}": must be a positive integer`
1455
+ );
1456
+ }
1457
+ return { interval: input.interval, frequency: input.frequency };
1458
+ }
1459
+
1460
+ // src/infrastructure/providers/bachs/bachs-money.ts
1461
+ var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([]);
1462
+ var THREE_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
1463
+ "BHD",
1464
+ "IQD",
1465
+ "JOD",
1466
+ "KWD",
1467
+ "LYD",
1468
+ "OMR",
1469
+ "TND"
1470
+ ]);
1471
+ var DECIMAL_RE = /^(\d+)(?:\.(\d+))?$/;
1472
+ function currencyExponent(currency) {
1473
+ if (THREE_DECIMAL_CURRENCIES.has(currency)) {
1474
+ throw new ValidationError(
1475
+ `Bachs amounts are two-decimal; ${currency} needs three decimal places and cannot be represented`
1476
+ );
1477
+ }
1478
+ return ZERO_DECIMAL_CURRENCIES.has(currency) ? 0 : 2;
1479
+ }
1480
+ function toBachsAmount(money) {
1481
+ const exponent = currencyExponent(money.currency);
1482
+ const minor = String(money.amount);
1483
+ if (exponent === 0) return minor;
1484
+ const padded = minor.padStart(exponent + 1, "0");
1485
+ return `${padded.slice(0, -exponent)}.${padded.slice(-exponent)}`;
1486
+ }
1487
+ function fromBachsAmount(value, currency) {
1488
+ const match = DECIMAL_RE.exec(value);
1489
+ if (!match) {
1490
+ throw new ValidationError(`Invalid amount from Bachs: "${value}"`);
1491
+ }
1492
+ const exponent = currencyExponent(currency);
1493
+ const whole = match[1] ?? "0";
1494
+ const fraction = match[2] ?? "";
1495
+ const significantFraction = fraction.slice(0, exponent);
1496
+ const surplus = fraction.slice(exponent);
1497
+ if (surplus.length > 0 && !/^0+$/.test(surplus)) {
1498
+ throw new ValidationError(
1499
+ `Amount "${value}" carries more precision than ${currency} allows`
1500
+ );
1501
+ }
1502
+ const fractionPadded = significantFraction.padEnd(exponent, "0");
1503
+ const scaled = BigInt(whole) * 10n ** BigInt(exponent) + (fractionPadded.length > 0 ? BigInt(fractionPadded) : 0n);
1504
+ if (scaled > BigInt(Number.MAX_SAFE_INTEGER)) {
1505
+ throw new ValidationError(`Amount "${value}" exceeds the maximum supported value`);
1506
+ }
1507
+ return Money({ amount: Number(scaled), currency });
1508
+ }
1509
+
1510
+ // src/infrastructure/providers/bachs/bachs-primitives.ts
1511
+ function toBachsDate(value) {
1512
+ if (!value) return void 0;
1513
+ const parsed = new Date(value);
1514
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed;
1515
+ }
1516
+ function emptyMetadata3() {
1517
+ return Object.freeze({});
1518
+ }
1519
+ function mapBachsMetadata(raw) {
1520
+ if (!raw || typeof raw !== "object") return emptyMetadata3();
1521
+ const mapped = {};
1522
+ for (const [key, value] of Object.entries(raw)) {
1523
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1524
+ mapped[key] = value;
1525
+ }
1526
+ }
1527
+ return Object.freeze(mapped);
1528
+ }
1529
+
1530
+ // src/infrastructure/providers/bachs/bachs-subscription-mapper.ts
1531
+ var BACHS = Provider("bachs");
1532
+ var EPOCH = /* @__PURE__ */ new Date(0);
1533
+ function mapBachsPrice(price) {
1534
+ const currency = price.currency;
1535
+ return {
1536
+ priceType: price.price_type ?? "fixed",
1537
+ currency,
1538
+ amount: price.amount ? fromBachsAmount(price.amount, currency) : void 0,
1539
+ presetAmount: price.preset_amount ? fromBachsAmount(price.preset_amount, currency) : void 0,
1540
+ minimumAmount: price.minimum_amount ? fromBachsAmount(price.minimum_amount, currency) : void 0,
1541
+ maximumAmount: price.maximum_amount ? fromBachsAmount(price.maximum_amount, currency) : void 0,
1542
+ currencyOptions: (price.currency_options ?? []).map(mapBachsCurrencyOption)
1543
+ };
1544
+ }
1545
+ function mapBachsCurrencyOption(option) {
1546
+ const currency = option.currency;
1547
+ return {
1548
+ currency,
1549
+ amount: option.amount ? fromBachsAmount(option.amount, currency) : void 0,
1550
+ minimumAmount: option.minimum_amount ? fromBachsAmount(option.minimum_amount, currency) : void 0,
1551
+ maximumAmount: option.maximum_amount ? fromBachsAmount(option.maximum_amount, currency) : void 0
1552
+ };
1553
+ }
1554
+ function mapBachsProduct(product) {
1555
+ return {
1556
+ id: product.id,
1557
+ providerId: BACHS,
1558
+ name: product.name,
1559
+ description: product.description ?? void 0,
1560
+ price: mapBachsPrice(product.price),
1561
+ // An unrecognised status must never look sellable, so it maps to archived.
1562
+ status: product.status === "archived" ? "archived" : product.status === "active" ? "active" : "archived",
1563
+ billingCycle: product.billing_cycle ? RecurringCadence(product.billing_cycle) : void 0,
1564
+ trialPeriod: product.trial_period ? RecurringCadence(product.trial_period) : void 0,
1565
+ metadata: mapBachsMetadata(product.metadata),
1566
+ createdAt: toBachsDate(product.created_at) ?? EPOCH,
1567
+ updatedAt: toBachsDate(product.updated_at) ?? toBachsDate(product.created_at) ?? EPOCH,
1568
+ archivedAt: toBachsDate(product.archived_at)
1569
+ };
1570
+ }
1571
+ function mapBachsProductListResponse(response) {
1572
+ const pagination = response.pagination;
1573
+ const limit = pagination.limit ?? response.items.length;
1574
+ const offset = pagination.offset ?? 0;
1575
+ return {
1576
+ items: response.items.map(mapBachsProduct),
1577
+ total: pagination.total ?? response.items.length,
1578
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1579
+ perPage: limit,
1580
+ nextCursor: pagination.next_cursor ?? null
1581
+ };
1582
+ }
1583
+ function mapBachsSubscriptionCustomer(customer) {
1584
+ return {
1585
+ id: customer.customer_id,
1586
+ email: customer.email,
1587
+ phone: customer.phone_number ?? void 0,
1588
+ name: customer.name ?? void 0,
1589
+ metadata: mapBachsMetadata(customer.metadata)
1590
+ };
1591
+ }
1592
+ function mapBachsSubscriptionStatus(status, trialEnd, canceledAt, fallback) {
1593
+ switch (status) {
1594
+ case "trialing":
1595
+ return { kind: "trialing", trialEnd: trialEnd ?? fallback };
1596
+ case "active":
1597
+ return { kind: "active" };
1598
+ case "past_due":
1599
+ return { kind: "pastDue" };
1600
+ case "unpaid":
1601
+ return { kind: "unpaid" };
1602
+ case "canceled":
1603
+ return { kind: "canceled", canceledAt: canceledAt ?? fallback };
1604
+ case "paused":
1605
+ return { kind: "paused" };
1606
+ default:
1607
+ return { kind: "paused" };
1608
+ }
1609
+ }
1610
+ function mapBachsSubscription(subscription) {
1611
+ const createdAt = toBachsDate(subscription.created_at) ?? EPOCH;
1612
+ const trialEnd = toBachsDate(subscription.trial_end);
1613
+ const canceledAt = toBachsDate(subscription.canceled_at);
1614
+ const periodStart = toBachsDate(subscription.current_period_start) ?? createdAt;
1615
+ return {
1616
+ id: subscription.id,
1617
+ providerId: BACHS,
1618
+ customer: mapBachsSubscriptionCustomer(subscription.customer),
1619
+ productId: subscription.product?.id,
1620
+ productName: subscription.product?.name,
1621
+ status: mapBachsSubscriptionStatus(subscription.status, trialEnd, canceledAt, createdAt),
1622
+ amount: fromBachsAmount(subscription.amount, subscription.currency),
1623
+ billingCycle: RecurringCadence(subscription.billing_cycle),
1624
+ quantity: subscription.quantity ?? 1,
1625
+ currentPeriodStart: periodStart,
1626
+ currentPeriodEnd: toBachsDate(subscription.current_period_end) ?? periodStart,
1627
+ nextBilledAt: toBachsDate(subscription.next_billed_at),
1628
+ cancelAtPeriodEnd: subscription.cancel_at_period_end ?? false,
1629
+ canceledAt,
1630
+ createdAt,
1631
+ metadata: mapBachsMetadata(subscription.metadata)
1632
+ };
1633
+ }
1634
+ function mapBachsSubscriptionListResponse(response) {
1635
+ const pagination = response.pagination;
1636
+ const limit = pagination.limit ?? response.items.length;
1637
+ const offset = pagination.offset ?? 0;
1638
+ return {
1639
+ items: response.items.map(mapBachsSubscription),
1640
+ total: pagination.total ?? response.items.length,
1641
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1642
+ perPage: limit,
1643
+ nextCursor: pagination.next_cursor ?? null
1644
+ };
1645
+ }
1646
+ function mapBachsCustomer(customer) {
1647
+ return {
1648
+ id: customer.customer_id,
1649
+ email: customer.email,
1650
+ phone: "phone_number" in customer ? customer.phone_number ?? void 0 : void 0,
1651
+ name: customer.name ?? void 0,
1652
+ metadata: mapBachsMetadata(customer.metadata)
1653
+ };
1654
+ }
1655
+ function mapBachsCustomerListResponse(response) {
1656
+ const pagination = response.pagination;
1657
+ const limit = pagination.limit ?? response.items.length;
1658
+ const offset = pagination.offset ?? 0;
1659
+ return {
1660
+ items: response.items.map(mapBachsCustomer),
1661
+ total: pagination.total ?? response.items.length,
1662
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1663
+ perPage: limit,
1664
+ nextCursor: pagination.next_cursor ?? null
1665
+ };
1666
+ }
1667
+ function mapBachsPortalSession(session) {
1668
+ return { id: session.id, url: session.url };
1669
+ }
1670
+ function buildCurrencyOptionInput(option) {
1671
+ return {
1672
+ currency: option.currency,
1673
+ amount: option.amount ? toBachsAmount(option.amount) : void 0,
1674
+ minimum_amount: option.minimumAmount ? toBachsAmount(option.minimumAmount) : void 0,
1675
+ maximum_amount: option.maximumAmount ? toBachsAmount(option.maximumAmount) : void 0
1676
+ };
1677
+ }
1678
+ function buildPriceInput(price) {
1679
+ return {
1680
+ currency: price.currency,
1681
+ price_type: price.priceType,
1682
+ amount: price.amount ? toBachsAmount(price.amount) : void 0,
1683
+ preset_amount: price.presetAmount ? toBachsAmount(price.presetAmount) : void 0,
1684
+ minimum_amount: price.minimumAmount ? toBachsAmount(price.minimumAmount) : void 0,
1685
+ maximum_amount: price.maximumAmount ? toBachsAmount(price.maximumAmount) : void 0,
1686
+ currency_options: price.currencyOptions?.map(buildCurrencyOptionInput)
1687
+ };
1688
+ }
1689
+ function buildBachsCreateProduct(input) {
1690
+ return {
1691
+ name: input.name,
1692
+ description: input.description,
1693
+ price: buildPriceInput(input.price),
1694
+ billing_cycle: input.billingCycle,
1695
+ trial_period: input.trialPeriod,
1696
+ metadata: input.metadata ? { ...input.metadata } : void 0
1697
+ };
1698
+ }
1699
+ function buildBachsUpdateProduct(input) {
1700
+ const price = input.amount !== void 0 || input.currencyOptions !== void 0 ? {
1701
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
1702
+ currency_options: input.currencyOptions?.map(buildCurrencyOptionInput)
1703
+ } : void 0;
1704
+ return {
1705
+ name: input.name,
1706
+ description: input.description,
1707
+ price,
1708
+ trial_period: input.trialPeriod,
1709
+ metadata: input.metadata ? { ...input.metadata } : void 0
1710
+ };
1711
+ }
1712
+ function buildBachsUpdateSubscription(input) {
1713
+ return {
1714
+ product_id: input.productId,
1715
+ trial_end: input.trialEnd?.toISOString(),
1716
+ payment_method_id: input.paymentMethodId,
1717
+ metadata: input.metadata ? { ...input.metadata } : void 0,
1718
+ proration_behavior: input.prorationBehavior
1719
+ };
1720
+ }
1721
+ function buildBachsCancelSubscription(input) {
1722
+ if (input.atPeriodEnd === void 0 && input.reason === void 0) return void 0;
1723
+ return { cancel_at_period_end: input.atPeriodEnd, reason: input.reason };
1724
+ }
1725
+ function buildBachsCreateCustomer(input) {
1726
+ return {
1727
+ email: input.email,
1728
+ name: input.name,
1729
+ phone_number: input.phone,
1730
+ metadata: input.metadata ? { ...input.metadata } : void 0
1731
+ };
1732
+ }
1733
+ function buildBachsUpdateCustomer(input) {
1734
+ return {
1735
+ email: input.email,
1736
+ name: input.name,
1737
+ phone_number: input.phone,
1738
+ metadata: input.metadata ? { ...input.metadata } : void 0
1739
+ };
1740
+ }
1741
+
1742
+ // src/infrastructure/providers/bachs/bachs-subscription-client.ts
1743
+ var BachsSubscriptionClient = class {
1744
+ httpClient;
1745
+ logger;
1746
+ idGenerator;
1747
+ connection;
1748
+ constructor(connection, deps) {
1749
+ this.connection = connection;
1750
+ this.httpClient = deps.httpClient;
1751
+ this.logger = deps.logger;
1752
+ this.idGenerator = deps.idGenerator;
1753
+ }
1754
+ async listProducts(query) {
1755
+ const { limit } = resolveBachsPagination({ perPage: query.limit, cursor: query.cursor });
1756
+ const params = new URLSearchParams({ limit: String(limit) });
1757
+ if (query.cursor) params.set("cursor", query.cursor);
1758
+ if (query.includeArchived) params.set("include_archived", "true");
1759
+ this.logger.info("listing products", { provider: "bachs", query: params.toString() });
1760
+ const response = await this.request(
1761
+ "GET",
1762
+ `/v1/products?${params.toString()}`,
1763
+ "list products response"
1764
+ );
1765
+ return response.ok ? this.mapped(response.value, mapBachsProductListResponse, "list products response") : response;
1766
+ }
1767
+ async fetchProduct(id) {
1768
+ this.logger.info("fetching product", { provider: "bachs", productId: id });
1769
+ const response = await this.request(
1770
+ "GET",
1771
+ `/v1/products/${encodeURIComponent(id)}`,
1772
+ "fetch product response"
1773
+ );
1774
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1775
+ }
1776
+ async createProduct(input) {
1777
+ this.logger.info("creating product", { provider: "bachs", recurring: input.billingCycle !== void 0 });
1778
+ const response = await this.request(
1779
+ "POST",
1780
+ "/v1/products",
1781
+ "create product response",
1782
+ buildBachsCreateProduct(input)
1783
+ );
1784
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1785
+ }
1786
+ async updateProduct(id, input) {
1787
+ this.logger.info("updating product", { provider: "bachs", productId: id });
1788
+ const response = await this.request(
1789
+ "PATCH",
1790
+ `/v1/products/${encodeURIComponent(id)}`,
1791
+ "update product response",
1792
+ buildBachsUpdateProduct(input)
1793
+ );
1794
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1795
+ }
1796
+ async archiveProduct(id) {
1797
+ this.logger.info("archiving product", { provider: "bachs", productId: id });
1798
+ const response = await this.request(
1799
+ "POST",
1800
+ `/v1/products/${encodeURIComponent(id)}/archive`,
1801
+ "archive product response"
1802
+ );
1803
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1804
+ }
1805
+ async unarchiveProduct(id) {
1806
+ this.logger.info("unarchiving product", { provider: "bachs", productId: id });
1807
+ const response = await this.request(
1808
+ "POST",
1809
+ `/v1/products/${encodeURIComponent(id)}/unarchive`,
1810
+ "unarchive product response"
1811
+ );
1812
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1813
+ }
1814
+ async listSubscriptions(query) {
1815
+ const { limit, offset } = resolveBachsPagination({ page: query.page, perPage: query.limit });
1816
+ const params = new URLSearchParams({
1817
+ limit: String(limit),
1818
+ offset: String(offset)
1819
+ });
1820
+ if (query.customerId) params.set("customer_id", query.customerId);
1821
+ if (query.status) params.set("status", query.status);
1822
+ this.logger.info("listing subscriptions", { provider: "bachs", query: params.toString() });
1823
+ const response = await this.request(
1824
+ "GET",
1825
+ `/v1/subscriptions?${params.toString()}`,
1826
+ "list subscriptions response"
1827
+ );
1828
+ return response.ok ? this.mapped(response.value, mapBachsSubscriptionListResponse, "list subscriptions response") : response;
1829
+ }
1830
+ async fetchSubscription(id) {
1831
+ this.logger.info("fetching subscription", { provider: "bachs", subscriptionId: id });
1832
+ const response = await this.request(
1833
+ "GET",
1834
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1835
+ "fetch subscription response"
1836
+ );
1837
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1838
+ }
1839
+ async updateSubscription(id, input) {
1840
+ this.logger.info("updating subscription", { provider: "bachs", subscriptionId: id });
1841
+ const response = await this.request(
1842
+ "PATCH",
1843
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1844
+ "update subscription response",
1845
+ buildBachsUpdateSubscription(input)
1846
+ );
1847
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1848
+ }
1849
+ async cancelSubscription(id, input) {
1850
+ this.logger.info("canceling subscription", {
1851
+ provider: "bachs",
1852
+ subscriptionId: id,
1853
+ atPeriodEnd: input.atPeriodEnd ?? false
1854
+ });
1855
+ const response = await this.request(
1856
+ "DELETE",
1857
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1858
+ "cancel subscription response",
1859
+ buildBachsCancelSubscription(input)
1860
+ );
1861
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1862
+ }
1863
+ async listCustomers(query) {
1864
+ const { limit, offset } = resolveBachsPagination({ page: query.page, perPage: query.limit });
1865
+ const params = new URLSearchParams({
1866
+ limit: String(limit),
1867
+ offset: String(offset)
1868
+ });
1869
+ if (query.search) params.set("search", query.search);
1870
+ this.logger.info("listing customers", { provider: "bachs", query: params.toString() });
1871
+ const response = await this.request(
1872
+ "GET",
1873
+ `/v1/customers?${params.toString()}`,
1874
+ "list customers response"
1875
+ );
1876
+ return response.ok ? this.mapped(response.value, mapBachsCustomerListResponse, "list customers response") : response;
1877
+ }
1878
+ async fetchCustomer(id) {
1879
+ this.logger.info("fetching customer", { provider: "bachs", customerId: id });
1880
+ const response = await this.request(
1881
+ "GET",
1882
+ `/v1/customers/${encodeURIComponent(id)}`,
1883
+ "fetch customer response"
1884
+ );
1885
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1886
+ }
1887
+ async createCustomer(input) {
1888
+ this.logger.info("creating customer", { provider: "bachs" });
1889
+ const response = await this.request(
1890
+ "POST",
1891
+ "/v1/customers",
1892
+ "create customer response",
1893
+ buildBachsCreateCustomer(input)
1894
+ );
1895
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1896
+ }
1897
+ async updateCustomer(id, input) {
1898
+ this.logger.info("updating customer", { provider: "bachs", customerId: id });
1899
+ const response = await this.request(
1900
+ "PATCH",
1901
+ `/v1/customers/${encodeURIComponent(id)}`,
1902
+ "update customer response",
1903
+ buildBachsUpdateCustomer(input)
1904
+ );
1905
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1906
+ }
1907
+ async createPortalSession(customerId) {
1908
+ this.logger.info("creating customer portal session", { provider: "bachs", customerId });
1909
+ const response = await this.request(
1910
+ "POST",
1911
+ `/v1/customers/${encodeURIComponent(customerId)}/portal-sessions`,
1912
+ "create portal session response"
1913
+ );
1914
+ return response.ok ? this.mapped(response.value, mapBachsPortalSession, "create portal session response") : response;
1915
+ }
1916
+ mapped(value, mapper, context) {
1917
+ try {
1918
+ return ok(mapper(value));
1919
+ } catch (e) {
1920
+ return err(mapMapperError(e, { provider: "bachs", context }));
1921
+ }
1922
+ }
1923
+ async request(method, path, context, body) {
1924
+ const correlationId = this.idGenerator.generate();
1925
+ const result = await this.httpClient.send({
1926
+ method,
1927
+ url: `${this.connection.baseUrl}${path}`,
1928
+ headers: { Authorization: `Bearer ${this.connection.secretKey}` },
1929
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
1930
+ timeoutMs: this.connection.timeoutMs,
1931
+ correlationId
1932
+ });
1933
+ if (!result.ok) return result;
1934
+ try {
1935
+ return ok(JSON.parse(result.value.body));
1936
+ } catch (e) {
1937
+ return err(mapMapperError(e, { provider: "bachs", context }));
1938
+ }
1939
+ }
1940
+ };
1941
+
1942
+ // src/infrastructure/providers/bachs/bachs-mapper.ts
1943
+ var BACHS2 = Provider("bachs");
1944
+ function mapBachsPaymentStatus(status, context) {
1945
+ switch (status) {
1946
+ case "created":
1947
+ return { kind: "initialized" };
1948
+ case "processing":
1949
+ case "underpaid":
1950
+ return { kind: "pending" };
1951
+ case "succeeded":
1952
+ case "accepted":
1953
+ case "overpaid":
1954
+ return { kind: "success", paidAt: context.completedAt ?? context.updatedAt };
1955
+ case "failed":
1956
+ return {
1957
+ kind: "failed",
1958
+ reason: context.message ?? "payment_failed",
1959
+ failedAt: context.completedAt ?? context.updatedAt
1960
+ };
1961
+ case "expired":
1962
+ case "cancelled":
1963
+ return { kind: "abandoned" };
1964
+ case "refunded":
1965
+ case "partially_refunded":
1966
+ case "auto_refunded":
1967
+ return {
1968
+ kind: "refunded",
1969
+ refundedAt: context.completedAt ?? context.updatedAt,
1970
+ refundId: context.refunds?.[0] ?? "unknown"
1971
+ };
1972
+ default:
1973
+ return { kind: "pending" };
1974
+ }
1975
+ }
1976
+ function mapBachsChannel(method) {
1977
+ const raw = typeof method === "string" ? method : method?.type;
1978
+ if (typeof raw !== "string" || raw.length === 0) return void 0;
1979
+ const value = raw.toUpperCase();
1980
+ if (value === "CARD" || value.endsWith("_CARD")) return "card";
1981
+ if (value === "BANK" || value === "BANK_TRANSFER" || value.endsWith("_BANK_TRANSFER")) {
1982
+ return "bank_transfer";
1983
+ }
1984
+ if (value === "MOBILE_MONEY" || value.startsWith("MOMO")) return "mobile_money";
1985
+ if (value === "CRYPTO" || value.startsWith("CRYPTO")) return "crypto";
1986
+ return void 0;
1987
+ }
1988
+ function mapFee2(fees, amount) {
1989
+ if (!fees?.amount) return {};
1990
+ try {
1991
+ const fee = fromBachsAmount(fees.amount, fees.currency);
1992
+ if (fee.currency !== amount.currency) return { fees: fee };
1993
+ const net = amount.amount - fee.amount;
1994
+ return {
1995
+ fees: fee,
1996
+ netAmount: net >= 0 ? Money({ amount: net, currency: amount.currency }) : void 0
1997
+ };
1998
+ } catch {
1999
+ return {};
2000
+ }
2001
+ }
2002
+ function mapPaymentCustomer(customer) {
2003
+ return {
2004
+ // The Bachs payment object does not carry the customer id, only the
2005
+ // denormalised name and email.
2006
+ id: "unknown",
2007
+ email: customer?.email ?? "",
2008
+ name: customer?.name ?? void 0
2009
+ };
2010
+ }
2011
+ function mapBachsPaymentResponse(payment) {
2012
+ const currency = payment.currency;
2013
+ const amount = fromBachsAmount(payment.amount, currency);
2014
+ const createdAt = toBachsDate(payment.created_at) ?? /* @__PURE__ */ new Date();
2015
+ const updatedAt = toBachsDate(payment.updated_at) ?? createdAt;
2016
+ const completedAt = toBachsDate(payment.completed_at);
2017
+ const status = mapBachsPaymentStatus(payment.status, {
2018
+ message: payment.message,
2019
+ updatedAt,
2020
+ completedAt,
2021
+ refunds: payment.refunds
2022
+ });
2023
+ return {
2024
+ id: payment.payment_id,
2025
+ providerId: BACHS2,
2026
+ reference: PaymentReference(payment.reference ?? payment.payment_id),
2027
+ amount,
2028
+ ...mapFee2(payment.fees, amount),
2029
+ status,
2030
+ customer: mapPaymentCustomer(payment.customer),
2031
+ channel: mapBachsChannel(payment.payment_method),
2032
+ attempts: Object.freeze([]),
2033
+ metadata: mapBachsMetadata(payment.meta),
2034
+ createdAt,
2035
+ updatedAt,
2036
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2037
+ failureReason: status.kind === "failed" ? status.reason : void 0
2038
+ };
2039
+ }
2040
+ function mapBachsCheckoutSessionCreated(response, request, now) {
2041
+ const createdAt = toBachsDate(response.created_at) ?? now;
2042
+ return {
2043
+ id: response.checkout_id,
2044
+ providerId: BACHS2,
2045
+ reference: request.reference,
2046
+ // A catalog checkout is priced by Bachs; the total arrives with the
2047
+ // payment (verify/fetch/webhook) rather than from the request.
2048
+ ...request.amount ? { amount: request.amount } : {},
2049
+ status: { kind: "initialized" },
2050
+ customer: request.customer.kind === "inline" ? request.customer.customer : {
2051
+ id: "pending",
2052
+ email: request.customer.kind === "new" ? request.customer.email : "unknown",
2053
+ phone: request.customer.kind === "new" ? request.customer.phone : void 0,
2054
+ name: request.customer.kind === "new" ? request.customer.name : void 0
2055
+ },
2056
+ authorizationUrl: response.checkout_url,
2057
+ attempts: Object.freeze([]),
2058
+ metadata: request.metadata ? Object.freeze({ ...request.metadata }) : emptyMetadata3(),
2059
+ createdAt,
2060
+ updatedAt: createdAt
2061
+ };
2062
+ }
2063
+ function mapBachsCheckoutSession(session) {
2064
+ if (session.charge) {
2065
+ return mapBachsPaymentResponse(session.charge);
2066
+ }
2067
+ const currency = session.currency;
2068
+ const amount = fromBachsAmount(session.amount, currency);
2069
+ const createdAt = toBachsDate(session.created_at) ?? /* @__PURE__ */ new Date();
2070
+ const updatedAt = toBachsDate(session.updated_at) ?? createdAt;
2071
+ const completedAt = toBachsDate(session.completed_at);
2072
+ const paymentFailed = session.payment_status === "failed";
2073
+ const status = paymentFailed ? { kind: "failed", reason: "checkout_failed", failedAt: completedAt ?? updatedAt } : session.status === "expired" || session.status === "cancelled" ? { kind: "abandoned" } : session.status === "completed" ? { kind: "success", paidAt: completedAt ?? updatedAt } : { kind: "pending" };
2074
+ const customer = session.customer;
2075
+ const details = session.customer_details;
2076
+ return {
2077
+ id: session.checkout_id,
2078
+ providerId: BACHS2,
2079
+ reference: PaymentReference(session.reference ?? session.checkout_id),
2080
+ amount,
2081
+ status,
2082
+ customer: {
2083
+ id: customer?.id ?? "unknown",
2084
+ email: customer?.email ?? details?.email ?? "",
2085
+ name: customer?.name ?? details?.name ?? void 0
2086
+ },
2087
+ channel: mapBachsChannel(session.payment_method),
2088
+ attempts: Object.freeze([]),
2089
+ metadata: mapBachsMetadata(session.metadata),
2090
+ createdAt,
2091
+ updatedAt,
2092
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2093
+ failureReason: status.kind === "failed" ? status.reason : void 0
2094
+ };
2095
+ }
2096
+ function mapBachsPaymentListItem(item) {
2097
+ const currency = item.currency;
2098
+ const amount = fromBachsAmount(item.amount, currency);
2099
+ const completedAt = toBachsDate(item.completed_at);
2100
+ const createdAt = toBachsDate(item.transaction_date) ?? completedAt ?? /* @__PURE__ */ new Date();
2101
+ const updatedAt = completedAt ?? createdAt;
2102
+ const id = item.id ?? item.reference ?? "unknown";
2103
+ const status = mapBachsPaymentStatus(item.status, { updatedAt, completedAt });
2104
+ return {
2105
+ id,
2106
+ providerId: BACHS2,
2107
+ reference: PaymentReference(item.reference ?? id),
2108
+ amount,
2109
+ ...item.fee ? mapFee2({ amount: item.fee, currency: item.currency }, amount) : {},
2110
+ ...mapSettlementAmount(item),
2111
+ status,
2112
+ channel: mapBachsChannel(item.payment_method),
2113
+ customer: {
2114
+ id: "unknown",
2115
+ email: item.customer_email,
2116
+ name: item.customer_name
2117
+ },
2118
+ attempts: Object.freeze([]),
2119
+ metadata: mapBachsMetadata(item.meta),
2120
+ createdAt,
2121
+ updatedAt,
2122
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2123
+ failureReason: status.kind === "failed" ? status.reason : void 0
2124
+ };
2125
+ }
2126
+ function mapSettlementAmount(item) {
2127
+ const value = item.settlement_amount;
2128
+ const currency = item.settlement_currency;
2129
+ if (!value || !currency) return {};
2130
+ try {
2131
+ return { settlementAmount: fromBachsAmount(value, Currency(currency)) };
2132
+ } catch {
2133
+ return {};
2134
+ }
2135
+ }
2136
+ function mapBachsPaymentListResponse(response) {
2137
+ const pagination = response.pagination;
2138
+ const limit = pagination.limit ?? response.items.length;
2139
+ const offset = pagination.offset ?? 0;
2140
+ return {
2141
+ items: response.items.map(mapBachsPaymentListItem),
2142
+ total: pagination.total ?? response.items.length,
2143
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
2144
+ perPage: limit,
2145
+ nextCursor: pagination.next_cursor ?? null
2146
+ };
2147
+ }
2148
+ function mapBachsRefundResponse(refund, currency) {
2149
+ return {
2150
+ id: refund.refund_id,
2151
+ paymentId: refund.charge_id,
2152
+ amount: fromBachsAmount(refund.requested_amount, currency),
2153
+ status: mapBachsRefundStatus(refund.status),
2154
+ reason: refund.reason ?? "",
2155
+ reference: refund.reference,
2156
+ createdAt: toBachsDate(refund.created_at) ?? /* @__PURE__ */ new Date(),
2157
+ completedAt: toBachsDate(refund.completed_at)
2158
+ };
2159
+ }
2160
+ function mapBachsRefundStatus(status) {
2161
+ switch (status) {
2162
+ case "success":
2163
+ return "succeeded";
2164
+ case "failed":
2165
+ return "failed";
2166
+ case "processing":
2167
+ return "processing";
2168
+ default:
2169
+ return "processing";
2170
+ }
2171
+ }
2172
+ function mapBachsPayoutResponse(payout, fallbackRecipientCode, now = /* @__PURE__ */ new Date()) {
2173
+ const currency = payout.currency;
2174
+ const amount = fromBachsAmount(payout.amount, currency);
2175
+ const createdAt = toBachsDate(payout.created_at) ?? now;
2176
+ const completedAt = toBachsDate(payout.completed_at);
2177
+ const status = mapBachsPayoutStatus(payout.status, payout.failure_reason, completedAt, createdAt);
2178
+ const sourceCurrency = payout.source_currency ?? void 0;
2179
+ const fee = mapSecondaryAmount(payout.fee, sourceCurrency);
2180
+ const totalDebited = mapSecondaryAmount(payout.total_debited, sourceCurrency);
2181
+ return {
2182
+ id: payout.id,
2183
+ providerId: BACHS2,
2184
+ amount,
2185
+ recipient: {
2186
+ code: payout.destination ?? fallbackRecipientCode,
2187
+ name: "unknown",
2188
+ accountNumber: "unknown",
2189
+ bankCode: "unknown",
2190
+ currency,
2191
+ createdAt,
2192
+ metadata: emptyMetadata3()
2193
+ },
2194
+ status,
2195
+ reference: payout.reference ?? payout.id,
2196
+ transferCode: payout.id,
2197
+ ...fee ? { fee } : {},
2198
+ ...totalDebited ? { totalDebited } : {},
2199
+ ...sourceCurrency ? { sourceCurrency } : {},
2200
+ createdAt,
2201
+ completedAt,
2202
+ failureReason: status.kind === "failed" ? status.reason : void 0,
2203
+ metadata: emptyMetadata3()
2204
+ };
2205
+ }
2206
+ function mapSecondaryAmount(value, currency) {
2207
+ if (!value || !currency) return void 0;
2208
+ try {
2209
+ return fromBachsAmount(value, currency);
2210
+ } catch {
2211
+ return void 0;
2212
+ }
2213
+ }
2214
+ function mapBachsPayoutStatus(status, failureReason, completedAt, createdAt) {
2215
+ switch (status) {
2216
+ case "pending":
2217
+ return { kind: "pending" };
2218
+ case "processing":
2219
+ return { kind: "processing" };
2220
+ case "completed":
2221
+ return { kind: "succeeded", settledAt: completedAt ?? createdAt };
2222
+ case "failed":
2223
+ return {
2224
+ kind: "failed",
2225
+ reason: failureReason ?? "payout_failed",
2226
+ failedAt: completedAt ?? createdAt
2227
+ };
2228
+ default:
2229
+ return { kind: "pending" };
2230
+ }
2231
+ }
2232
+ function mapBachsPayoutListResponse(response, options) {
2233
+ return {
2234
+ items: response.items.map((payout) => mapBachsPayoutResponse(payout, "unknown", options.now)),
2235
+ total: response.total,
2236
+ page: options.page,
2237
+ perPage: options.perPage,
2238
+ nextCursor: null
2239
+ };
2240
+ }
2241
+ function mapBachsChargeSettlement(charge) {
2242
+ const settlement = charge.settlement_currency;
2243
+ if (!settlement) return void 0;
2244
+ try {
2245
+ return {
2246
+ settlementCurrency: Currency(settlement),
2247
+ chargeCurrency: charge.currency ? Currency(charge.currency) : void 0
2248
+ };
2249
+ } catch {
2250
+ return void 0;
2251
+ }
2252
+ }
2253
+ function mapBachsDestinationResponse(destination, input, now) {
2254
+ return {
2255
+ code: destination.id,
2256
+ name: destination.account_name ?? destination.name ?? input.name,
2257
+ accountNumber: destination.account_number ?? input.accountNumber,
2258
+ bankCode: destination.bank_code ?? input.bankCode,
2259
+ // Prefer what the provider stored: it normalises and may reject values.
2260
+ currency: destination.currency ? Currency(destination.currency) : input.currency,
2261
+ status: destination.status,
2262
+ createdAt: toBachsDate(destination.created_at) ?? now,
2263
+ metadata: input.metadata ? Object.freeze({ ...input.metadata }) : emptyMetadata3()
2264
+ };
2265
+ }
2266
+ function mapBachsBankListResponse(response, currency) {
2267
+ return Object.freeze(
2268
+ response.banks.map((bank) => ({
2269
+ code: bank.code,
2270
+ name: bank.name,
2271
+ currency
2272
+ }))
2273
+ );
2274
+ }
2275
+ function normalizeBachsWebhookType(eventType) {
2276
+ switch (eventType) {
2277
+ case "collection.succeeded":
2278
+ return "payment.succeeded";
2279
+ case "collection.failed":
2280
+ return "payment.failed";
2281
+ case "collection.underpaid":
2282
+ return "payment.underpaid";
2283
+ case "checkout.completed":
2284
+ return "checkout.completed";
2285
+ case "checkout.expired":
2286
+ return "checkout.expired";
2287
+ case "refund.created":
2288
+ return "refund.initiated";
2289
+ case "refund.paid":
2290
+ return "refund.succeeded";
2291
+ case "refund.failed":
2292
+ return "refund.failed";
2293
+ case "payout.created":
2294
+ return "transfer.initiated";
2295
+ case "payout.paid":
2296
+ return "transfer.succeeded";
2297
+ case "payout.failed":
2298
+ return "transfer.failed";
2299
+ case "customer.subscription.created":
2300
+ return "subscription.created";
2301
+ case "customer.subscription.updated":
2302
+ return "subscription.updated";
2303
+ case "customer.subscription.deleted":
2304
+ return "subscription.canceled";
2305
+ case "invoice.created":
2306
+ return "invoice.created";
2307
+ case "invoice.paid":
2308
+ return "invoice.paid";
2309
+ case "invoice.payment_failed":
2310
+ return "invoice.payment_failed";
2311
+ case "customer.created":
2312
+ return "customer.created";
2313
+ case "customer.updated":
2314
+ return "customer.updated";
2315
+ case "dispute.created":
2316
+ return "dispute.created";
2317
+ case "dispute.updated":
2318
+ return "dispute.updated";
2319
+ case "conversion.completed":
2320
+ return "conversion.completed";
2321
+ case "conversion.failed":
2322
+ return "conversion.failed";
2323
+ case "payment_method.saved":
2324
+ return "payment_method.saved";
2325
+ default:
2326
+ return "unknown";
2327
+ }
2328
+ }
2329
+ function mapBachsWebhookEvent(envelope, receivedAt) {
2330
+ return {
2331
+ id: envelope.id,
2332
+ provider: BACHS2,
2333
+ type: normalizeBachsWebhookType(envelope.type),
2334
+ originalType: envelope.type,
2335
+ createdAt: toBachsDate(envelope.created_at) ?? receivedAt,
2336
+ receivedAt,
2337
+ payload: envelope.data ?? {},
2338
+ raw: envelope
2339
+ };
2340
+ }
2341
+ var BACHS_DEFAULT_TOLERANCE_SECONDS = 300;
2342
+ var V2_HEADER = "x-bachs-signature-v2";
2343
+ var SIGNATURE_HEADER2 = "x-bachs-signature";
2344
+ var TIMESTAMP_HEADER = "x-bachs-timestamp";
2345
+ function parseBachsWebhook(headers, rawBody, config, clock) {
2346
+ if (!config.webhookSecret) {
2347
+ return err(
2348
+ new WebhookValidationError(
2349
+ "Bachs webhook verification requires the endpoint signing secret (whsec_...)"
2350
+ )
2351
+ );
2352
+ }
2353
+ const candidates = collectSignatures(headers);
2354
+ if (!candidates) {
2355
+ return err(new WebhookValidationError("Missing Bachs webhook signature headers"));
2356
+ }
2357
+ const nowSeconds = Math.floor(clock.now().getTime() / 1e3);
2358
+ const tolerance = normalizeTolerance(config.toleranceSeconds);
2359
+ if (Math.abs(nowSeconds - candidates.timestamp) > tolerance) {
2360
+ return err(new WebhookValidationError("Bachs webhook timestamp is outside the tolerance window"));
2361
+ }
2362
+ const expected = sign(`${candidates.timestamp}.${rawBody}`, config.webhookSecret);
2363
+ const matched = candidates.signatures.some((signature) => constantTimeEquals(signature, expected));
2364
+ if (!matched) {
2365
+ return err(new WebhookValidationError("Invalid Bachs webhook signature"));
2366
+ }
2367
+ let envelope;
2368
+ try {
2369
+ envelope = JSON.parse(rawBody);
2370
+ } catch {
2371
+ return err(new WebhookValidationError("Invalid webhook body: not valid JSON"));
2372
+ }
2373
+ if (!envelope.id || !envelope.type) {
2374
+ return err(new WebhookValidationError("Invalid webhook body: missing event id or type"));
2375
+ }
2376
+ try {
2377
+ return ok(mapBachsWebhookEvent(envelope, clock.now()));
2378
+ } catch (e) {
2379
+ return err(
2380
+ new WebhookValidationError(
2381
+ `Failed to parse Bachs webhook payload: ${e instanceof Error ? e.message : String(e)}`
2382
+ )
2383
+ );
2384
+ }
2385
+ }
2386
+ function collectSignatures(headers) {
2387
+ const v2 = findHeader2(headers, V2_HEADER);
2388
+ if (v2) {
2389
+ const parsed = parseSignatureV2(v2);
2390
+ if (parsed) return parsed;
2391
+ }
2392
+ const signature = findHeader2(headers, SIGNATURE_HEADER2);
2393
+ const timestamp = findHeader2(headers, TIMESTAMP_HEADER);
2394
+ if (!signature || !timestamp) return void 0;
2395
+ const seconds = Number.parseInt(timestamp, 10);
2396
+ if (!Number.isFinite(seconds)) return void 0;
2397
+ return { timestamp: seconds, signatures: [signature] };
2398
+ }
2399
+ function parseSignatureV2(header) {
2400
+ let timestamp;
2401
+ const signatures = [];
2402
+ for (const part of header.split(",")) {
2403
+ const separator = part.indexOf("=");
2404
+ if (separator < 0) continue;
2405
+ const key = part.slice(0, separator).trim();
2406
+ const value = part.slice(separator + 1).trim();
2407
+ if (key === "t") {
2408
+ const seconds = Number.parseInt(value, 10);
2409
+ if (Number.isFinite(seconds)) timestamp = seconds;
2410
+ } else if (key === "v1" && value.length > 0) {
2411
+ signatures.push(value);
2412
+ }
2413
+ }
2414
+ if (timestamp === void 0 || signatures.length === 0) return void 0;
2415
+ return { timestamp, signatures };
2416
+ }
2417
+ function normalizeTolerance(configured) {
2418
+ if (configured === void 0 || !Number.isFinite(configured) || configured <= 0) {
2419
+ return BACHS_DEFAULT_TOLERANCE_SECONDS;
2420
+ }
2421
+ return configured;
2422
+ }
2423
+ function sign(message, secret) {
2424
+ return createHmac("sha256", secret).update(message, "utf8").digest("hex");
2425
+ }
2426
+ function constantTimeEquals(a, b) {
2427
+ const left = Buffer.from(a, "utf8");
2428
+ const right = Buffer.from(b, "utf8");
2429
+ if (left.length !== right.length) return false;
2430
+ return timingSafeEqual(left, right);
2431
+ }
2432
+ function findHeader2(headers, name) {
2433
+ const lower = name.toLowerCase();
2434
+ for (const key of Object.keys(headers)) {
2435
+ if (key.toLowerCase() === lower) {
2436
+ return headers[key];
2437
+ }
2438
+ }
2439
+ return void 0;
2440
+ }
2441
+
2442
+ // src/infrastructure/providers/bachs/bachs-adapter.ts
2443
+ var COLLECTION_CURRENCIES = [
2444
+ "USD",
2445
+ "NGN",
2446
+ "GHS",
2447
+ "KES",
2448
+ "MWK",
2449
+ "RWF",
2450
+ "TZS",
2451
+ "UGX",
2452
+ "XAF",
2453
+ "XOF",
2454
+ "ZMW"
2455
+ ].map((code) => code);
2456
+ var PAYOUT_CURRENCIES = [
2457
+ "NGN",
2458
+ "GHS",
2459
+ "KES",
2460
+ "TZS",
2461
+ "UGX",
2462
+ "USD",
2463
+ "GBP",
2464
+ "EUR",
2465
+ "CAD"
2466
+ ].map((code) => code);
2467
+ var CHANNELS = [
2468
+ "card",
2469
+ "bank_transfer",
2470
+ "mobile_money",
2471
+ "crypto"
2472
+ ];
2473
+ var BACHS_CAPABILITIES = {
2474
+ supportsAuthorizationUrl: true,
2475
+ supportsRecurring: true,
2476
+ supportsPartialRefund: true,
2477
+ supportsWebhooks: true,
2478
+ supportsTransfers: true,
2479
+ // Bachs documents `Idempotency-Key` on public POST/PATCH and a per-refund
2480
+ // `idempotency_key`, so retries are deduplicated by the provider.
2481
+ supportsIdempotencyKey: true,
2482
+ supportedCurrencies: COLLECTION_CURRENCIES,
2483
+ supportedChannels: CHANNELS,
2484
+ supportedTransferCurrencies: PAYOUT_CURRENCIES
2485
+ };
2486
+ var COUNTRY_BY_CURRENCY = {
2487
+ NGN: "NG",
2488
+ GHS: "GH",
2489
+ KES: "KE",
2490
+ TZS: "TZ",
2491
+ UGX: "UG",
2492
+ ZMW: "ZM",
2493
+ MWK: "MW",
2494
+ RWF: "RW"
2495
+ };
2496
+ var CARD_CORRIDORS = {
2497
+ USD: "USD_CARD",
2498
+ NGN: "NGN_CARD"
2499
+ };
2500
+ var MOMO_CORRIDORS = {
2501
+ GHS: "MOMO_GHS",
2502
+ KES: "MOMO_KES",
2503
+ TZS: "MOMO_TZS",
2504
+ UGX: "MOMO_UGX",
2505
+ XAF: "MOMO_XAF",
2506
+ XOF: "MOMO_XOF",
2507
+ RWF: "MOMO_RWF",
2508
+ MWK: "MOMO_MWK",
2509
+ ZMW: "MOMO_ZMW"
2510
+ };
2511
+ var BachsAdapter = class {
2512
+ id;
2513
+ capabilities;
2514
+ httpClient;
2515
+ logger;
2516
+ clock;
2517
+ idGenerator;
2518
+ connection;
2519
+ billing;
2520
+ constructor(config, deps) {
2521
+ const connection = createBachsConnection(config);
2522
+ this.id = "bachs";
2523
+ this.capabilities = BACHS_CAPABILITIES;
2524
+ this.httpClient = deps.httpClient;
2525
+ this.logger = deps.logger;
2526
+ this.clock = deps.clock;
2527
+ this.idGenerator = deps.idGenerator;
2528
+ this.connection = connection;
2529
+ this.billing = new BachsSubscriptionClient(connection, deps);
2530
+ this.logger.debug("bachs adapter configured", {
2531
+ provider: this.id,
2532
+ environment: connection.environment
2533
+ });
2534
+ }
2535
+ async initialize(req) {
2536
+ const correlationId = req.correlationId ?? this.idGenerator.generate();
2537
+ const body = buildCheckoutSessionRequest(req, this.clock.now());
2538
+ if (req.channels && !body.payment_method_types) {
2539
+ this.logger.warn("bachs cannot restrict to the requested channels; offering all corridors", {
2540
+ provider: this.id,
2541
+ currency: req.amount?.currency ?? "unknown",
2542
+ channels: req.channels.join(","),
2543
+ correlationId
2544
+ });
2545
+ }
2546
+ this.logger.info("initializing payment", {
2547
+ provider: this.id,
2548
+ reference: req.reference,
2549
+ correlationId,
2550
+ // A catalog checkout is priced by Bachs, so the amount may be unknown here.
2551
+ amount: req.amount ? String(req.amount.amount) : "provider-priced",
2552
+ currency: req.amount?.currency ?? "unknown"
2553
+ });
2554
+ const result = await this.httpClient.send({
2555
+ method: "POST",
2556
+ url: `${this.connection.baseUrl}/v1/checkout-sessions`,
2557
+ headers: this.authHeaders(),
2558
+ body: JSON.stringify(body),
2559
+ timeoutMs: this.connection.timeoutMs,
2560
+ correlationId,
2561
+ idempotencyKey: req.idempotencyKey
2562
+ });
2563
+ if (!result.ok) {
2564
+ this.logger.error("initialize failed", result.error, {
2565
+ provider: this.id,
2566
+ reference: req.reference,
2567
+ correlationId
2568
+ });
2569
+ return result;
2570
+ }
2571
+ try {
2572
+ const response = JSON.parse(result.value.body);
2573
+ return ok(mapBachsCheckoutSessionCreated(response, req, this.clock.now()));
2574
+ } catch (e) {
2575
+ return err(mapMapperError(e, { provider: this.id, context: "initialize response" }));
2576
+ }
2577
+ }
2578
+ /**
2579
+ * Bachs has no lookup by your own reference on any endpoint. Verification is
2580
+ * therefore by provider id: a checkout id (`chk_`) reads the checkout
2581
+ * session, and a payment id (`ch_`, `pay_`, `chrg_`) reads the payment.
2582
+ * Fulfilment should still come from webhooks, not from this call.
2583
+ */
2584
+ async verify(reference) {
2585
+ const value = String(reference);
2586
+ if (value.startsWith("pay_") || value.startsWith("ch_") || value.startsWith("chrg_")) {
2587
+ return this.fetch(value);
2588
+ }
2589
+ if (!value.startsWith("chk_")) {
2590
+ return err(
2591
+ new ProviderBadRequestError(
2592
+ "Bachs can only verify by checkout id (chk_) or payment id (ch_/pay_/chrg_); keep the id returned by initialize() or sent in the webhook",
2593
+ { provider: this.id }
2594
+ )
2595
+ );
2596
+ }
2597
+ const correlationId = this.idGenerator.generate();
2598
+ this.logger.info("verifying checkout session", {
2599
+ provider: this.id,
2600
+ checkoutId: value,
2601
+ correlationId
2602
+ });
2603
+ const result = await this.httpClient.send({
2604
+ method: "GET",
2605
+ url: `${this.connection.baseUrl}/v1/checkout-sessions/${encodeURIComponent(value)}`,
2606
+ headers: this.authHeaders(),
2607
+ timeoutMs: this.connection.timeoutMs,
2608
+ correlationId
2609
+ });
2610
+ if (!result.ok) return result;
2611
+ try {
2612
+ const response = JSON.parse(result.value.body);
2613
+ return ok(mapBachsCheckoutSession(response));
2614
+ } catch (e) {
2615
+ return err(mapMapperError(e, { provider: this.id, context: "verify response" }));
2616
+ }
2617
+ }
2618
+ async fetch(id) {
2619
+ const correlationId = this.idGenerator.generate();
2620
+ this.logger.info("fetching payment", {
2621
+ provider: this.id,
2622
+ paymentId: id,
2623
+ correlationId
2624
+ });
2625
+ const result = await this.httpClient.send({
2626
+ method: "GET",
2627
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(id)}`,
2628
+ headers: this.authHeaders(),
2629
+ timeoutMs: this.connection.timeoutMs,
2630
+ correlationId
2631
+ });
2632
+ if (!result.ok) return result;
2633
+ try {
2634
+ const response = JSON.parse(result.value.body);
2635
+ return ok(mapBachsPaymentResponse(response));
2636
+ } catch (e) {
2637
+ return err(mapMapperError(e, { provider: this.id, context: "fetch response" }));
2638
+ }
2639
+ }
2640
+ async list(query = {}) {
2641
+ const correlationId = this.idGenerator.generate();
2642
+ const { limit, offset, clamped } = resolveBachsPagination(query);
2643
+ const params = new URLSearchParams({ limit: String(limit) });
2644
+ if (clamped) {
2645
+ this.logger.warn("perPage clamped to the provider maximum", {
2646
+ provider: this.id,
2647
+ requested: String(query.perPage),
2648
+ limit,
2649
+ correlationId
2650
+ });
2651
+ }
2652
+ if (query.cursor) {
2653
+ params.set("cursor", query.cursor);
2654
+ } else if (query.page) {
2655
+ params.set("offset", String(offset));
2656
+ }
2657
+ if (query.status) params.set("status_filter", query.status);
2658
+ if (query.from || query.to || query.customer) {
2659
+ this.logger.warn("bachs payments list does not support from/to/customer filters; ignoring them", {
2660
+ provider: this.id,
2661
+ correlationId
2662
+ });
2663
+ }
2664
+ this.logger.info("listing payments", {
2665
+ provider: this.id,
2666
+ correlationId,
2667
+ query: params.toString()
2668
+ });
2669
+ const result = await this.httpClient.send({
2670
+ method: "GET",
2671
+ url: `${this.connection.baseUrl}/v1/payments?${params.toString()}`,
2672
+ headers: this.authHeaders(),
2673
+ timeoutMs: this.connection.timeoutMs,
2674
+ correlationId
2675
+ });
2676
+ if (!result.ok) return result;
2677
+ try {
2678
+ const response = JSON.parse(result.value.body);
2679
+ return ok(mapBachsPaymentListResponse(response));
2680
+ } catch (e) {
2681
+ return err(mapMapperError(e, { provider: this.id, context: "list response" }));
2682
+ }
2683
+ }
2684
+ /**
2685
+ * Bachs allows one non-failed refund per charge and settles refunds
2686
+ * asynchronously. The charge is read first for its `is_refundable`
2687
+ * pre-check, and the settlement side is read for the currency a partial
2688
+ * refund must be expressed in (it differs from the charge currency
2689
+ * whenever Bachs' adaptive pricing converts the charge).
2690
+ */
2691
+ async refund(input) {
2692
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
2693
+ this.logger.info("refunding payment", {
2694
+ provider: this.id,
2695
+ paymentId: input.paymentId,
2696
+ correlationId
2697
+ });
2698
+ const chargeResult = await this.httpClient.send({
2699
+ method: "GET",
2700
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(input.paymentId)}`,
2701
+ headers: this.authHeaders(),
2702
+ timeoutMs: this.connection.timeoutMs,
2703
+ correlationId
2704
+ });
2705
+ if (!chargeResult.ok) return chargeResult;
2706
+ try {
2707
+ const charge = JSON.parse(chargeResult.value.body);
2708
+ if (charge.is_refundable === false) {
2709
+ return err(
2710
+ new ProviderBadRequestError(
2711
+ `Bachs payment ${input.paymentId} is not refundable`,
2712
+ { provider: this.id }
2713
+ )
2714
+ );
2715
+ }
2716
+ const chargeCurrency = Currency(charge.currency);
2717
+ const settlement = await this.resolveSettlement(input.paymentId, correlationId);
2718
+ const refundCurrency = settlement ?? chargeCurrency;
2719
+ if (settlement && settlement !== chargeCurrency) {
2720
+ this.logger.info("refund sized in the settlement currency", {
2721
+ provider: this.id,
2722
+ chargeCurrency,
2723
+ settlementCurrency: settlement,
2724
+ correlationId
2725
+ });
2726
+ }
2727
+ if (input.amount && input.amount.currency !== refundCurrency) {
2728
+ return err(
2729
+ new ValidationError(
2730
+ `Refund amount is in ${input.amount.currency} but Bachs refunds payment ${input.paymentId} in ${refundCurrency}; pass the amount in ${refundCurrency}`
2731
+ )
2732
+ );
2733
+ }
2734
+ const body = {
2735
+ charge_id: input.paymentId,
2736
+ reference: input.reference,
2737
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
2738
+ reason: input.reason,
2739
+ idempotency_key: input.idempotencyKey
2740
+ };
2741
+ const result = await this.httpClient.send({
2742
+ method: "POST",
2743
+ url: `${this.connection.baseUrl}/v1/refunds`,
2744
+ headers: this.authHeaders(),
2745
+ body: JSON.stringify(body),
2746
+ timeoutMs: this.connection.timeoutMs,
2747
+ correlationId,
2748
+ idempotencyKey: input.idempotencyKey
2749
+ });
2750
+ if (!result.ok) return result;
2751
+ const response = JSON.parse(result.value.body);
2752
+ return ok(mapBachsRefundResponse(response, refundCurrency));
2753
+ } catch (e) {
2754
+ return err(mapMapperError(e, { provider: this.id, context: "refund response" }));
2755
+ }
2756
+ }
2757
+ async fetchRefund(refundId) {
2758
+ const correlationId = this.idGenerator.generate();
2759
+ this.logger.info("fetching refund", {
2760
+ provider: this.id,
2761
+ refundId,
2762
+ correlationId
2763
+ });
2764
+ const result = await this.httpClient.send({
2765
+ method: "GET",
2766
+ url: `${this.connection.baseUrl}/v1/refunds/${encodeURIComponent(refundId)}`,
2767
+ headers: this.authHeaders(),
2768
+ timeoutMs: this.connection.timeoutMs,
2769
+ correlationId
2770
+ });
2771
+ if (!result.ok) return result;
2772
+ try {
2773
+ const refund = JSON.parse(result.value.body);
2774
+ const currency = await this.resolveRefundCurrency(refund.charge_id, correlationId);
2775
+ if (!currency.ok) return currency;
2776
+ return ok(mapBachsRefundResponse(refund, currency.value));
2777
+ } catch (e) {
2778
+ return err(mapMapperError(e, { provider: this.id, context: "fetch refund response" }));
2779
+ }
2780
+ }
2781
+ async createTransferQuote(input) {
2782
+ const correlationId = this.idGenerator.generate();
2783
+ if (input.fromCurrency === input.toCurrency) {
2784
+ return err(
2785
+ new ValidationError(
2786
+ `A payout quote converts between two currencies; ${input.fromCurrency} to ${input.fromCurrency} needs none (send the payout amount directly)`
2787
+ )
2788
+ );
2789
+ }
2790
+ const body = {
2791
+ from_currency: input.fromCurrency,
2792
+ to_currency: input.toCurrency,
2793
+ amount: toBachsAmount(input.amount)
2794
+ };
2795
+ this.logger.info("creating payout quote", {
2796
+ provider: this.id,
2797
+ fromCurrency: input.fromCurrency,
2798
+ toCurrency: input.toCurrency,
2799
+ correlationId
2800
+ });
2801
+ const result = await this.httpClient.send({
2802
+ method: "POST",
2803
+ url: `${this.connection.baseUrl}/v1/payouts/quotes`,
2804
+ headers: this.authHeaders(),
2805
+ body: JSON.stringify(body),
2806
+ timeoutMs: this.connection.timeoutMs,
2807
+ correlationId
2808
+ });
2809
+ if (!result.ok) return result;
2810
+ try {
2811
+ const response = JSON.parse(result.value.body);
2812
+ return ok({
2813
+ id: response.quote_id,
2814
+ providerId: this.id,
2815
+ fromCurrency: Currency(response.from_currency),
2816
+ toCurrency: Currency(response.to_currency),
2817
+ fromAmount: fromBachsQuoteAmount(response.from_amount, response.from_currency),
2818
+ toAmount: fromBachsQuoteAmount(response.to_amount, response.to_currency),
2819
+ exchangeRate: response.exchange_rate,
2820
+ expiresAt: response.expires_at ? new Date(response.expires_at) : void 0
2821
+ });
2822
+ } catch (e) {
2823
+ return err(mapMapperError(e, { provider: this.id, context: "payout quote response" }));
2824
+ }
2825
+ }
2826
+ async parseWebhook(headers, rawBody) {
2827
+ return parseBachsWebhook(
2828
+ headers,
2829
+ rawBody,
2830
+ {
2831
+ webhookSecret: this.connection.webhookSecret,
2832
+ toleranceSeconds: this.connection.webhookToleranceSeconds
2833
+ },
2834
+ this.clock
2835
+ );
2836
+ }
2837
+ // -------------------------------------------------------------------------
2838
+ // SubscriptionProvider — delegated to the billing client
2839
+ // -------------------------------------------------------------------------
2840
+ listProducts(query = {}) {
2841
+ return this.billing.listProducts(query);
2842
+ }
2843
+ fetchProduct(id) {
2844
+ return this.billing.fetchProduct(id);
2845
+ }
2846
+ createProduct(input) {
2847
+ return this.billing.createProduct(input);
2848
+ }
2849
+ updateProduct(id, input) {
2850
+ return this.billing.updateProduct(id, input);
2851
+ }
2852
+ archiveProduct(id) {
2853
+ return this.billing.archiveProduct(id);
2854
+ }
2855
+ unarchiveProduct(id) {
2856
+ return this.billing.unarchiveProduct(id);
2857
+ }
2858
+ listSubscriptions(query = {}) {
2859
+ return this.billing.listSubscriptions(query);
2860
+ }
2861
+ fetchSubscription(id) {
2862
+ return this.billing.fetchSubscription(id);
2863
+ }
2864
+ updateSubscription(id, input) {
2865
+ return this.billing.updateSubscription(id, input);
2866
+ }
2867
+ cancelSubscription(id, input = {}) {
2868
+ return this.billing.cancelSubscription(id, input);
2869
+ }
2870
+ listCustomers(query = {}) {
2871
+ return this.billing.listCustomers(query);
2872
+ }
2873
+ fetchCustomer(id) {
2874
+ return this.billing.fetchCustomer(id);
2875
+ }
2876
+ createCustomer(input) {
2877
+ return this.billing.createCustomer(input);
2878
+ }
2879
+ updateCustomer(id, input) {
2880
+ return this.billing.updateCustomer(id, input);
2881
+ }
2882
+ createPortalSession(customerId) {
2883
+ return this.billing.createPortalSession(customerId);
2884
+ }
2885
+ async health() {
2886
+ const start = Date.now();
2887
+ try {
2888
+ const result = await this.httpClient.send({
2889
+ method: "GET",
2890
+ url: `${this.connection.baseUrl}/v1/payments?limit=1`,
2891
+ headers: this.authHeaders(),
2892
+ timeoutMs: 5e3
2893
+ });
2894
+ if (!result.ok) {
2895
+ this.logger.warn("health check failed", {
2896
+ provider: this.id,
2897
+ code: result.error.code,
2898
+ httpStatus: result.error.httpStatus,
2899
+ message: result.error.message
2900
+ });
2901
+ }
2902
+ return {
2903
+ healthy: result.ok,
2904
+ latencyMs: Date.now() - start,
2905
+ timestamp: this.clock.now()
2906
+ };
2907
+ } catch (error) {
2908
+ this.logger.warn("health check threw", {
2909
+ provider: this.id,
2910
+ message: error instanceof Error ? error.message : String(error)
2911
+ });
2912
+ return {
2913
+ healthy: false,
2914
+ latencyMs: Date.now() - start,
2915
+ timestamp: this.clock.now()
2916
+ };
2917
+ }
2918
+ }
2919
+ /**
2920
+ * Banks are resolved by country: `/v1/reference/banks` falls back to the
2921
+ * platform's own country (or 400s) when none is given, so labelling the
2922
+ * response with an unrelated currency would be wrong. The country comes from
2923
+ * the caller when given, and from the currency map otherwise.
2924
+ */
2925
+ async listBankCodes(input) {
2926
+ const correlationId = this.idGenerator.generate();
2927
+ const country = input.country ?? COUNTRY_BY_CURRENCY[input.currency];
2928
+ if (!country) {
2929
+ return err(
2930
+ new ValidationError(
2931
+ `Bachs lists banks by country, and ${input.currency} does not identify one; pass { currency, country: "NG" }`
2932
+ )
2933
+ );
2934
+ }
2935
+ this.logger.info("listing bank codes", {
2936
+ provider: this.id,
2937
+ currency: input.currency,
2938
+ country,
2939
+ correlationId
2940
+ });
2941
+ const result = await this.httpClient.send({
2942
+ method: "GET",
2943
+ url: `${this.connection.baseUrl}/v1/reference/banks?country=${encodeURIComponent(country)}`,
2944
+ headers: this.authHeaders(),
2945
+ timeoutMs: this.connection.timeoutMs,
2946
+ correlationId
2947
+ });
2948
+ if (!result.ok) return result;
2949
+ try {
2950
+ const response = JSON.parse(result.value.body);
2951
+ return ok(mapBachsBankListResponse(response, input.currency));
2952
+ } catch (e) {
2953
+ return err(mapMapperError(e, { provider: this.id, context: "bank list response" }));
2954
+ }
2955
+ }
2956
+ async resolveAccount(input) {
2957
+ const correlationId = this.idGenerator.generate();
2958
+ const country = input.country ?? COUNTRY_BY_CURRENCY[input.currency];
2959
+ const body = {
2960
+ account_number: input.accountNumber,
2961
+ bank_code: input.bankCode,
2962
+ country
2963
+ };
2964
+ this.logger.info("resolving account", {
2965
+ provider: this.id,
2966
+ bankCode: input.bankCode,
2967
+ country,
2968
+ correlationId
2969
+ });
2970
+ const result = await this.httpClient.send({
2971
+ method: "POST",
2972
+ url: `${this.connection.baseUrl}/v1/misc/bank-accounts/resolve`,
2973
+ headers: this.authHeaders(),
2974
+ body: JSON.stringify(body),
2975
+ timeoutMs: this.connection.timeoutMs,
2976
+ correlationId
2977
+ });
2978
+ if (!result.ok) return result;
2979
+ try {
2980
+ const response = JSON.parse(result.value.body);
2981
+ if (!response.resolved) {
2982
+ return err(
2983
+ new ProviderError(response.message ?? "Account could not be resolved", {
2984
+ provider: this.id,
2985
+ httpStatus: 422,
2986
+ isRetryable: false
2987
+ })
2988
+ );
2989
+ }
2990
+ return ok({
2991
+ accountName: response.account_name ?? "",
2992
+ accountNumber: response.account_number ?? input.accountNumber
2993
+ });
2994
+ } catch (e) {
2995
+ return err(mapMapperError(e, { provider: this.id, context: "resolve account response" }));
2996
+ }
2997
+ }
2998
+ async createRecipient(input) {
2999
+ const correlationId = this.idGenerator.generate();
3000
+ const body = buildPayoutDestinationRequest(input);
3001
+ this.logger.info("creating payout destination", {
3002
+ provider: this.id,
3003
+ type: body.type,
3004
+ bankCode: input.bankCode,
3005
+ correlationId
3006
+ });
3007
+ const result = await this.httpClient.send({
3008
+ method: "POST",
3009
+ url: `${this.connection.baseUrl}/v1/payouts/destinations`,
3010
+ headers: this.authHeaders(),
3011
+ body: JSON.stringify(body),
3012
+ timeoutMs: this.connection.timeoutMs,
3013
+ correlationId
3014
+ });
3015
+ if (!result.ok) return result;
3016
+ try {
3017
+ const response = JSON.parse(result.value.body);
3018
+ return ok(mapBachsDestinationResponse(response, input, this.clock.now()));
3019
+ } catch (e) {
3020
+ return err(mapMapperError(e, { provider: this.id, context: "create destination response" }));
3021
+ }
3022
+ }
3023
+ async initiateTransfer(input) {
3024
+ const hasAmount = input.amount !== void 0;
3025
+ const hasQuote = input.quoteId !== void 0;
3026
+ if (hasAmount === hasQuote) {
3027
+ throw new ValidationError(
3028
+ "A Bachs payout takes exactly one of amount (same-currency) or quoteId (cross-currency)"
3029
+ );
3030
+ }
3031
+ if (input.amount && input.currency !== input.amount.currency) {
3032
+ throw new ValidationError(
3033
+ `Transfer currency ${input.currency} does not match amount currency ${input.amount.currency}`
3034
+ );
3035
+ }
3036
+ if (input.reference.length > 128) {
3037
+ throw new ValidationError(
3038
+ `Bachs payout references are limited to 128 characters (got ${input.reference.length})`
3039
+ );
3040
+ }
3041
+ if (input.accountReference) {
3042
+ this.logger.warn("accountReference is ignored by Bachs (Paystack-only field)", {
3043
+ provider: this.id,
3044
+ correlationId: input.correlationId ?? "unknown"
3045
+ });
3046
+ }
3047
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
3048
+ const body = {
3049
+ destination: input.recipientCode,
3050
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
3051
+ quote_id: input.quoteId,
3052
+ reference: input.reference,
3053
+ metadata: input.metadata ? { ...input.metadata } : void 0
3054
+ };
3055
+ this.logger.info("initiating payout", {
3056
+ provider: this.id,
3057
+ reference: input.reference,
3058
+ correlationId
3059
+ });
3060
+ const result = await this.httpClient.send({
3061
+ method: "POST",
3062
+ url: `${this.connection.baseUrl}/v1/payouts`,
3063
+ headers: this.authHeaders(),
3064
+ body: JSON.stringify(body),
3065
+ timeoutMs: this.connection.timeoutMs,
3066
+ correlationId,
3067
+ idempotencyKey: input.idempotencyKey
3068
+ });
3069
+ if (!result.ok) return result;
3070
+ try {
3071
+ const response = JSON.parse(result.value.body);
3072
+ const now = this.clock.now();
3073
+ const recipient = await this.lookupDestination(response.destination, now);
3074
+ return ok(mapBachsPayoutResponse(response, recipient?.code ?? input.recipientCode, now));
3075
+ } catch (e) {
3076
+ return err(mapMapperError(e, { provider: this.id, context: "initiate payout response" }));
3077
+ }
3078
+ }
3079
+ async fetchTransfer(id) {
3080
+ const correlationId = this.idGenerator.generate();
3081
+ this.logger.info("fetching payout", {
3082
+ provider: this.id,
3083
+ payoutId: id,
3084
+ correlationId
3085
+ });
3086
+ const result = await this.httpClient.send({
3087
+ method: "GET",
3088
+ url: `${this.connection.baseUrl}/v1/payouts/${encodeURIComponent(id)}`,
3089
+ headers: this.authHeaders(),
3090
+ timeoutMs: this.connection.timeoutMs,
3091
+ correlationId
3092
+ });
3093
+ if (!result.ok) return result;
3094
+ try {
3095
+ const response = JSON.parse(result.value.body);
3096
+ const now = this.clock.now();
3097
+ const recipient = await this.lookupDestination(response.destination, now);
3098
+ const transfer = mapBachsPayoutResponse(response, recipient?.code ?? "unknown", now);
3099
+ return ok(recipient ? { ...transfer, recipient } : transfer);
3100
+ } catch (e) {
3101
+ return err(mapMapperError(e, { provider: this.id, context: "fetch payout response" }));
3102
+ }
3103
+ }
3104
+ async listTransfers(query = {}) {
3105
+ const correlationId = this.idGenerator.generate();
3106
+ const page = query.page ?? 1;
3107
+ const { limit, offset, clamped } = resolveBachsPagination(query);
3108
+ const params = new URLSearchParams({
3109
+ limit: String(limit),
3110
+ offset: String(offset)
3111
+ });
3112
+ if (clamped) {
3113
+ this.logger.warn("perPage clamped to the provider maximum", {
3114
+ provider: this.id,
3115
+ requested: String(query.perPage),
3116
+ limit,
3117
+ correlationId
3118
+ });
3119
+ }
3120
+ this.logger.info("listing payouts", {
3121
+ provider: this.id,
3122
+ correlationId,
3123
+ query: params.toString()
3124
+ });
3125
+ const result = await this.httpClient.send({
3126
+ method: "GET",
3127
+ url: `${this.connection.baseUrl}/v1/payouts?${params.toString()}`,
3128
+ headers: this.authHeaders(),
3129
+ timeoutMs: this.connection.timeoutMs,
3130
+ correlationId
3131
+ });
3132
+ if (!result.ok) return result;
3133
+ try {
3134
+ const response = JSON.parse(result.value.body);
3135
+ return ok(mapBachsPayoutListResponse(response, { page, perPage: limit, now: this.clock.now() }));
3136
+ } catch (e) {
3137
+ return err(mapMapperError(e, { provider: this.id, context: "list payouts response" }));
3138
+ }
3139
+ }
3140
+ /**
3141
+ * Resolves the settlement currency for a charge.
3142
+ *
3143
+ * `GET /v1/payments/charges/{charge_id}` publishes it, but it accepts only a
3144
+ * charge id (`ch_`/`chrg_`): passing a checkout id (`chk_`) returns
3145
+ * `404 Charge not found` (verified against the sandbox). A caller who only
3146
+ * holds the checkout id is therefore served from the payment's own currency,
3147
+ * which is the same currency for every non-converted charge.
3148
+ */
3149
+ async resolveSettlement(chargeId, correlationId) {
3150
+ if (!chargeId.startsWith("ch_") && !chargeId.startsWith("chrg_")) {
3151
+ this.logger.debug("charge-status needs a charge id; skipping settlement lookup", {
3152
+ provider: this.id,
3153
+ chargeId,
3154
+ correlationId
3155
+ });
3156
+ return void 0;
3157
+ }
3158
+ const result = await this.httpClient.send({
3159
+ method: "GET",
3160
+ url: `${this.connection.baseUrl}/v1/payments/charges/${encodeURIComponent(chargeId)}`,
3161
+ headers: this.authHeaders(),
3162
+ timeoutMs: this.connection.timeoutMs,
3163
+ correlationId
3164
+ });
3165
+ if (!result.ok) {
3166
+ this.logger.warn("settlement currency unavailable; falling back to the charge currency", {
3167
+ provider: this.id,
3168
+ chargeId,
3169
+ correlationId,
3170
+ error: result.error.code
3171
+ });
3172
+ return void 0;
3173
+ }
3174
+ try {
3175
+ const response = JSON.parse(result.value.body);
3176
+ return mapBachsChargeSettlement(response)?.settlementCurrency;
3177
+ } catch {
3178
+ return void 0;
3179
+ }
3180
+ }
3181
+ /**
3182
+ * `GET /v1/refunds/{id}` carries no currency, so it is read from the
3183
+ * settlement side of the charge, falling back to the payment's own currency.
3184
+ */
3185
+ async resolveRefundCurrency(chargeId, correlationId) {
3186
+ const settlement = await this.resolveSettlement(chargeId, correlationId);
3187
+ if (settlement) return ok(settlement);
3188
+ const paymentResult = await this.httpClient.send({
3189
+ method: "GET",
3190
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(chargeId)}`,
3191
+ headers: this.authHeaders(),
3192
+ timeoutMs: this.connection.timeoutMs,
3193
+ correlationId
3194
+ });
3195
+ if (!paymentResult.ok) return paymentResult;
3196
+ try {
3197
+ const payment = JSON.parse(paymentResult.value.body);
3198
+ return ok(Currency(payment.currency));
3199
+ } catch (e) {
3200
+ return err(mapMapperError(e, { provider: this.id, context: "refund currency lookup" }));
3201
+ }
3202
+ }
3203
+ /** Best-effort destination lookup; a failure must never fail the payout read. */
3204
+ async lookupDestination(destinationId, now) {
3205
+ if (!destinationId) return void 0;
3206
+ const result = await this.httpClient.send({
3207
+ method: "GET",
3208
+ url: `${this.connection.baseUrl}/v1/payouts/destinations/${encodeURIComponent(destinationId)}`,
3209
+ headers: this.authHeaders(),
3210
+ timeoutMs: this.connection.timeoutMs
3211
+ });
3212
+ if (!result.ok) return void 0;
3213
+ try {
3214
+ const destination = JSON.parse(result.value.body);
3215
+ return mapBachsDestinationResponse(destination, {
3216
+ name: destination.name,
3217
+ accountNumber: destination.account_number ?? "",
3218
+ bankCode: destination.bank_code ?? "",
3219
+ currency: destination.currency
3220
+ }, now);
3221
+ } catch {
3222
+ return void 0;
3223
+ }
3224
+ }
3225
+ authHeaders() {
3226
+ return {
3227
+ Authorization: `Bearer ${this.connection.secretKey}`
3228
+ };
3229
+ }
3230
+ };
3231
+ function buildCheckoutSessionRequest(req, now) {
3232
+ const productCart = req.products?.length ? req.products.map((item) => ({
3233
+ product_id: item.productId,
3234
+ quantity: item.quantity,
3235
+ amount: item.amount ? toBachsAmount(item.amount) : void 0
3236
+ })) : void 0;
3237
+ let pricing;
3238
+ if (!productCart) {
3239
+ const amount = req.amount;
3240
+ if (!amount) {
3241
+ throw new ValidationError("A Bachs checkout session needs either an amount or a product cart");
3242
+ }
3243
+ pricing = {
3244
+ currency: amount.currency,
3245
+ amount: toBachsAmount(amount),
3246
+ price_type: "fixed"
3247
+ };
3248
+ }
3249
+ const corridorCurrency = req.amount?.currency;
3250
+ return {
3251
+ ...productCart ? { product_cart: productCart } : { pricing },
3252
+ reference: req.reference,
3253
+ success_url: req.callbackUrl,
3254
+ customer: mapCustomerRequest(req.customer),
3255
+ metadata: req.metadata ? { ...req.metadata } : void 0,
3256
+ expires_in_minutes: expiresInMinutes(req.expiresAt, now),
3257
+ payment_method_types: req.channels && corridorCurrency ? mapChannelsToCorridors(req.channels, corridorCurrency) : void 0
3258
+ };
3259
+ }
3260
+ function mapCustomerRequest(customer) {
3261
+ switch (customer.kind) {
3262
+ case "existing":
3263
+ return { customer_id: customer.providerCustomerId };
3264
+ case "inline":
3265
+ return {
3266
+ email: customer.customer.email,
3267
+ name: customer.customer.name,
3268
+ phone_number: customer.customer.phone
3269
+ };
3270
+ case "new":
3271
+ return {
3272
+ email: customer.email,
3273
+ name: customer.name,
3274
+ phone_number: customer.phone
3275
+ };
3276
+ }
3277
+ }
3278
+ function mapChannelsToCorridors(channels, currencyCode) {
3279
+ const corridors = /* @__PURE__ */ new Set();
3280
+ for (const channel of channels) {
3281
+ switch (channel) {
3282
+ case "card": {
3283
+ const corridor = CARD_CORRIDORS[currencyCode];
3284
+ if (corridor) corridors.add(corridor);
3285
+ break;
3286
+ }
3287
+ case "bank_transfer":
3288
+ if (currencyCode === "NGN") corridors.add("NGN_BANK_TRANSFER");
3289
+ break;
3290
+ case "mobile_money": {
3291
+ const corridor = MOMO_CORRIDORS[currencyCode];
3292
+ if (corridor) corridors.add(corridor);
3293
+ break;
3294
+ }
3295
+ }
3296
+ }
3297
+ return corridors.size > 0 ? [...corridors] : void 0;
3298
+ }
3299
+ function buildPayoutDestinationRequest(input) {
3300
+ const type = input.type ?? "bank_account";
3301
+ if (type === "mobile_money" && !input.phoneNumber) {
3302
+ throw new ValidationError(
3303
+ 'A mobile-money payout destination needs phoneNumber (the wallet number); pass { type: "mobile_money", phoneNumber }'
3304
+ );
3305
+ }
3306
+ return {
3307
+ name: input.name,
3308
+ currency: input.currency,
3309
+ type,
3310
+ account_number: input.accountNumber,
3311
+ bank_code: input.bankCode,
3312
+ account_name: input.accountName,
3313
+ bank_name: input.bankName,
3314
+ phone_number: input.phoneNumber,
3315
+ mobile_provider: input.mobileProvider,
3316
+ sort_code: input.sortCode,
3317
+ routing_number: input.routingNumber,
3318
+ scheme: input.scheme,
3319
+ metadata: input.metadata ? { ...input.metadata } : void 0
3320
+ };
3321
+ }
3322
+ function expiresInMinutes(expiresAt, now) {
3323
+ if (!expiresAt) return void 0;
3324
+ const minutes = Math.ceil((expiresAt.getTime() - now.getTime()) / 6e4);
3325
+ return Math.min(Math.max(minutes, 1), 1440);
3326
+ }
3327
+ function fromBachsQuoteAmount(value, currency) {
3328
+ return fromBachsAmount(value, Currency(currency));
3329
+ }
3330
+
3331
+ // src/infrastructure/providers/bachs/register.ts
3332
+ var BACHS_ID = "bachs";
3333
+ registerProvider(BACHS_ID, (config, deps) => new BachsAdapter(config, deps));
3334
+
3335
+ // src/application/use-cases/initialize-payment.ts
3336
+ async function initializePayment(deps, input) {
3337
+ deps.logger.info("use-case: initializePayment", {
3338
+ reference: input.reference
3339
+ });
3340
+ const result = await deps.provider.initialize(input);
3341
+ if (!result.ok) {
3342
+ return result;
3343
+ }
3344
+ deps.eventBus.emit({
3345
+ type: "payment.initialized",
3346
+ payment: result.value,
3347
+ occurredAt: deps.clock.now(),
3348
+ correlationId: input.correlationId ?? deps.idGenerator.generate()
3349
+ });
3350
+ return result;
3351
+ }
3352
+
3353
+ // src/application/use-cases/verify-payment.ts
3354
+ async function verifyPayment(deps, reference) {
3355
+ deps.logger.info("use-case: verifyPayment", { reference });
3356
+ const result = await deps.provider.verify(reference);
3357
+ if (!result.ok) return result;
3358
+ const payment = result.value;
3359
+ if (payment.status.kind === "success") {
3360
+ deps.eventBus.emit({
3361
+ type: "payment.succeeded",
3362
+ payment,
3363
+ occurredAt: deps.clock.now(),
3364
+ correlationId: deps.idGenerator.generate()
3365
+ });
3366
+ } else if (payment.status.kind === "failed") {
3367
+ deps.eventBus.emit({
3368
+ type: "payment.failed",
3369
+ payment,
3370
+ reason: payment.failureReason ?? "unknown",
3371
+ occurredAt: deps.clock.now(),
3372
+ correlationId: deps.idGenerator.generate()
3373
+ });
3374
+ }
3375
+ return result;
3376
+ }
3377
+
3378
+ // src/application/use-cases/fetch-payment.ts
3379
+ async function fetchPayment(deps, id) {
3380
+ deps.logger.info("use-case: fetchPayment", { paymentId: id });
3381
+ return deps.provider.fetch(id);
3382
+ }
3383
+
3384
+ // src/application/use-cases/list-payments.ts
3385
+ async function listPayments(deps, query) {
3386
+ deps.logger.info("use-case: listPayments", {
3387
+ page: query.page ? String(query.page) : "1",
3388
+ perPage: query.perPage ? String(query.perPage) : "50"
3389
+ });
3390
+ return deps.provider.list(query);
3391
+ }
3392
+
3393
+ // src/application/services/payment-service.ts
3394
+ var PaymentService = class {
3395
+ constructor(provider, eventBus, logger, clock, idGenerator) {
3396
+ this.provider = provider;
3397
+ this.eventBus = eventBus;
3398
+ this.logger = logger;
3399
+ this.clock = clock;
3400
+ this.idGenerator = idGenerator;
3401
+ }
3402
+ provider;
3403
+ eventBus;
3404
+ logger;
3405
+ clock;
3406
+ idGenerator;
3407
+ async initialize(req) {
3408
+ return initializePayment(
3409
+ {
3410
+ provider: this.provider,
3411
+ eventBus: this.eventBus,
3412
+ logger: this.logger,
3413
+ clock: this.clock,
3414
+ idGenerator: this.idGenerator
3415
+ },
3416
+ req
3417
+ );
3418
+ }
3419
+ async verify(reference) {
3420
+ return verifyPayment(
3421
+ {
3422
+ provider: this.provider,
3423
+ eventBus: this.eventBus,
3424
+ logger: this.logger,
3425
+ clock: this.clock,
3426
+ idGenerator: this.idGenerator
3427
+ },
3428
+ reference
3429
+ );
3430
+ }
3431
+ async fetch(id) {
3432
+ return fetchPayment({ provider: this.provider, logger: this.logger }, id);
3433
+ }
3434
+ async list(query) {
3435
+ return listPayments({ provider: this.provider, logger: this.logger }, query);
3436
+ }
3437
+ };
3438
+
3439
+ // src/application/mappers/refund-result-mapper.ts
3440
+ function mapRefundResultToRefund(result, providerId, clock) {
3441
+ const status = mapDomainRefundStatus(result.status, result.completedAt, clock);
3442
+ return {
3443
+ id: result.id,
3444
+ paymentId: result.paymentId,
3445
+ providerId,
3446
+ amount: result.amount,
3447
+ reason: result.reason,
3448
+ status,
3449
+ ...result.providerStatus ? { providerStatus: result.providerStatus } : {},
3450
+ initiatedAt: result.createdAt,
3451
+ completedAt: result.completedAt,
3452
+ failureReason: result.status === "failed" ? result.reason : void 0,
3453
+ metadata: Object.freeze({})
3454
+ };
3455
+ }
3456
+ function mapDomainRefundStatus(status, completedAt, clock) {
3457
+ switch (status) {
3458
+ case "succeeded":
3459
+ return { kind: "succeeded", settledAt: completedAt ?? clock.now() };
3460
+ case "failed":
3461
+ return { kind: "failed", reason: "refund_failed", failedAt: completedAt ?? clock.now() };
3462
+ case "pending":
3463
+ case "processing":
3464
+ default:
3465
+ return { kind: "processing" };
3466
+ }
3467
+ }
3468
+
3469
+ // src/application/use-cases/refund-payment.ts
3470
+ async function refundPayment(deps, input) {
3471
+ deps.logger.info("use-case: refundPayment", {
3472
+ provider: deps.provider.id,
3473
+ paymentId: input.paymentId
3474
+ });
3475
+ if (input.amount && input.amount.amount <= 0) {
3476
+ return err(new ValidationError("Refund amount must be greater than zero"));
3477
+ }
3478
+ const correlationId = input.correlationId ?? deps.idGenerator.generate();
3479
+ const providerInput = {
3480
+ paymentId: input.paymentId,
3481
+ amount: input.amount,
3482
+ reason: input.reason,
3483
+ reference: input.reference ?? correlationId,
3484
+ idempotencyKey: input.idempotencyKey,
3485
+ correlationId
3486
+ };
3487
+ const result = await deps.provider.refund(providerInput);
3488
+ if (!result.ok) {
3489
+ deps.logger.error("use-case: refundPayment failed", result.error, {
3490
+ provider: deps.provider.id,
3491
+ paymentId: input.paymentId
3492
+ });
3493
+ return result;
3494
+ }
3495
+ const refund = mapRefundResultToRefund(result.value, deps.provider.id, deps.clock);
3496
+ const now = deps.clock.now();
3497
+ if (refund.status.kind === "succeeded") {
3498
+ deps.eventBus.emit({
3499
+ type: "refund.succeeded",
3500
+ refund,
3501
+ occurredAt: now,
3502
+ correlationId
3503
+ });
3504
+ } else if (refund.status.kind === "failed") {
3505
+ deps.eventBus.emit({
3506
+ type: "refund.failed",
3507
+ refund,
3508
+ reason: refund.failureReason ?? "refund_failed",
3509
+ occurredAt: now,
3510
+ correlationId
3511
+ });
3512
+ } else {
3513
+ deps.eventBus.emit({
3514
+ type: "refund.initiated",
3515
+ refund,
3516
+ occurredAt: now,
3517
+ correlationId
3518
+ });
3519
+ }
3520
+ return ok(refund);
3521
+ }
3522
+
3523
+ // src/application/use-cases/fetch-refund.ts
3524
+ async function fetchRefund(deps, refundId) {
3525
+ deps.logger.info("use-case: fetchRefund", {
3526
+ provider: deps.provider.id,
3527
+ refundId
3528
+ });
3529
+ if (!deps.provider.fetchRefund) {
3530
+ return err(new InternalError(
3531
+ `Provider ${deps.provider.id} does not support fetching individual refunds`
3532
+ ));
3533
+ }
3534
+ const result = await deps.provider.fetchRefund(refundId);
3535
+ if (!result.ok) {
3536
+ deps.logger.error("use-case: fetchRefund failed", result.error, {
3537
+ provider: deps.provider.id,
3538
+ refundId
3539
+ });
3540
+ return result;
3541
+ }
3542
+ const refund = mapRefundResultToRefund(
3543
+ result.value,
3544
+ deps.provider.id,
3545
+ deps.clock
3546
+ );
3547
+ return ok(refund);
3548
+ }
3549
+
3550
+ // src/application/services/refund-service.ts
3551
+ var RefundService = class {
3552
+ provider;
3553
+ eventBus;
3554
+ logger;
3555
+ clock;
3556
+ idGenerator;
3557
+ constructor(provider, deps) {
3558
+ this.provider = provider;
3559
+ this.eventBus = deps.eventBus;
3560
+ this.logger = deps.logger;
3561
+ this.clock = deps.clock;
3562
+ this.idGenerator = deps.idGenerator;
3563
+ }
3564
+ async create(input) {
3565
+ return refundPayment(
3566
+ {
3567
+ provider: this.provider,
3568
+ eventBus: this.eventBus,
3569
+ logger: this.logger.child({ component: "refund-service" }),
3570
+ clock: this.clock,
3571
+ idGenerator: this.idGenerator
3572
+ },
3573
+ input
3574
+ );
3575
+ }
3576
+ async fetch(id) {
3577
+ return fetchRefund(
3578
+ {
3579
+ provider: this.provider,
3580
+ logger: this.logger.child({ component: "refund-service" }),
3581
+ clock: this.clock
3582
+ },
3583
+ id
3584
+ );
3585
+ }
3586
+ };
3587
+
3588
+ // src/application/use-cases/parse-webhook.ts
3589
+ async function parseWebhook(deps, input) {
3590
+ deps.logger.info("use-case: parseWebhook", {
3591
+ provider: deps.provider.id
3592
+ });
3593
+ let bodyString;
3594
+ if (typeof input.rawBody === "string") {
3595
+ bodyString = input.rawBody;
3596
+ } else {
3597
+ const converted = tryConvertBuffer(input.rawBody);
3598
+ if (!converted.ok) return converted;
3599
+ bodyString = converted.value;
3600
+ }
3601
+ const result = await deps.provider.parseWebhook(
3602
+ joinHeaders(input.headers ?? {}),
3603
+ bodyString,
3604
+ input.signature
3605
+ );
3606
+ if (!result.ok) {
3607
+ deps.logger.warn("use-case: parseWebhook failed", {
3608
+ provider: deps.provider.id,
3609
+ error: result.error.message
3610
+ });
3611
+ return result;
3612
+ }
3613
+ const event = result.value;
3614
+ deps.eventBus.emit({
3615
+ type: "webhook.received",
3616
+ provider: event.provider,
3617
+ eventId: event.id,
3618
+ eventType: event.type,
3619
+ originalType: event.originalType,
3620
+ payload: event.payload,
3621
+ occurredAt: deps.clock.now(),
3622
+ correlationId: deps.idGenerator.generate()
3623
+ });
3624
+ return result;
3625
+ }
3626
+ function tryConvertBuffer(body) {
3627
+ try {
3628
+ const decoder = new TextDecoder("utf-8", { fatal: true });
3629
+ return ok(decoder.decode(body));
3630
+ } catch {
3631
+ return err(new WebhookValidationError("Invalid webhook body: not valid UTF-8"));
3632
+ }
3633
+ }
3634
+ function joinHeaders(raw) {
3635
+ const result = {};
3636
+ for (const [key, value] of Object.entries(raw)) {
3637
+ if (value === void 0) continue;
3638
+ result[key] = typeof value === "string" ? value : value.join(", ");
3639
+ }
3640
+ return result;
3641
+ }
3642
+
3643
+ // src/application/services/webhook-service.ts
3644
+ var WebhookService = class {
3645
+ providers;
3646
+ eventBus;
3647
+ logger;
3648
+ clock;
3649
+ idGenerator;
3650
+ constructor(providers, deps) {
3651
+ this.providers = providers;
3652
+ this.eventBus = deps.eventBus;
3653
+ this.logger = deps.logger;
3654
+ this.clock = deps.clock;
3655
+ this.idGenerator = deps.idGenerator;
3656
+ }
3657
+ async receive(input) {
3658
+ const deps = {
3659
+ eventBus: this.eventBus,
3660
+ logger: this.logger.child({ component: "webhook-service" }),
3661
+ clock: this.clock,
3662
+ idGenerator: this.idGenerator
3663
+ };
3664
+ if (input.provider) {
3665
+ const provider = this.providers.get(input.provider);
3666
+ if (!provider) {
3667
+ return err(new WebhookValidationError(
3668
+ `Unknown provider: ${input.provider}`
3669
+ ));
3670
+ }
3671
+ return parseWebhook({ ...deps, provider }, input);
3672
+ }
3673
+ const errors = [];
3674
+ for (const [id, provider] of this.providers) {
3675
+ this.logger.debug("trying webhook provider", { provider: id });
3676
+ const result = await parseWebhook({ ...deps, provider }, input);
3677
+ if (result.ok) {
3678
+ this.logger.info("webhook matched provider", { provider: id });
3679
+ return result;
3680
+ }
3681
+ if (!result.ok) {
3682
+ errors.push(result.error);
3683
+ }
3684
+ }
3685
+ this.logger.warn("webhook rejected by all providers", {
3686
+ count: this.providers.size,
3687
+ errorMessages: errors.map((e) => e.message).join(", ")
3688
+ });
3689
+ return err(new WebhookValidationError(
3690
+ `Webhook rejected by all ${this.providers.size} configured provider(s)`
3691
+ ));
3692
+ }
3693
+ };
3694
+
3695
+ // src/application/use-cases/list-bank-codes.ts
3696
+ async function listBankCodes(deps, currency, options = {}) {
3697
+ deps.logger.info("use-case: listBankCodes", {
3698
+ provider: deps.provider.id,
3699
+ currency,
3700
+ country: options.country
3701
+ });
3702
+ return deps.provider.listBankCodes({ currency, country: options.country });
3703
+ }
3704
+
3705
+ // src/application/use-cases/resolve-account.ts
3706
+ async function resolveAccount(deps, input) {
3707
+ deps.logger.info("use-case: resolveAccount", {
3708
+ provider: deps.provider.id,
3709
+ bankCode: input.bankCode
3710
+ });
3711
+ return deps.provider.resolveAccount(input);
3712
+ }
3713
+
3714
+ // src/application/use-cases/create-recipient.ts
3715
+ async function createRecipient(deps, input) {
3716
+ deps.logger.info("use-case: createRecipient", {
3717
+ provider: deps.provider.id,
3718
+ bankCode: input.bankCode
3719
+ });
3720
+ return deps.provider.createRecipient(input);
3721
+ }
3722
+
3723
+ // src/application/use-cases/create-transfer-quote.ts
3724
+ async function createTransferQuote(deps, input) {
3725
+ deps.logger.info("use-case: createTransferQuote", {
3726
+ provider: deps.provider.id,
3727
+ fromCurrency: input.fromCurrency,
3728
+ toCurrency: input.toCurrency
3729
+ });
3730
+ if (!deps.provider.createTransferQuote) {
3731
+ return err(
3732
+ new UnsupportedProviderError(
3733
+ `Provider ${deps.provider.id} does not support cross-currency payout quotes`,
3734
+ { provider: deps.provider.id }
3735
+ )
3736
+ );
3737
+ }
3738
+ return deps.provider.createTransferQuote(input);
3739
+ }
3740
+
3741
+ // src/application/use-cases/initiate-transfer.ts
3742
+ async function initiateTransfer(deps, input) {
3743
+ deps.logger.info("use-case: initiateTransfer", {
3744
+ provider: deps.provider.id,
3745
+ reference: input.reference
3746
+ });
3747
+ const result = await deps.provider.initiateTransfer(input);
3748
+ if (!result.ok) {
3749
+ deps.logger.error("use-case: initiateTransfer failed", result.error, {
3750
+ provider: deps.provider.id,
3751
+ reference: input.reference
3752
+ });
3753
+ return result;
3754
+ }
3755
+ const correlationId = input.correlationId ?? deps.idGenerator.generate();
3756
+ if (result.value.status.kind === "failed") {
3757
+ deps.eventBus.emit({
3758
+ type: "transfer.failed",
3759
+ transfer: result.value,
3760
+ reason: result.value.failureReason ?? "transfer_failed",
3761
+ occurredAt: deps.clock.now(),
3762
+ correlationId
3763
+ });
3764
+ } else {
3765
+ deps.eventBus.emit({
3766
+ type: "transfer.initiated",
3767
+ transfer: result.value,
3768
+ occurredAt: deps.clock.now(),
3769
+ correlationId
3770
+ });
3771
+ }
3772
+ return result;
3773
+ }
3774
+
3775
+ // src/application/use-cases/fetch-transfer.ts
3776
+ async function fetchTransfer(deps, id) {
3777
+ deps.logger.info("use-case: fetchTransfer", {
3778
+ provider: deps.provider.id,
3779
+ transferId: id
3780
+ });
3781
+ return deps.provider.fetchTransfer(id);
3782
+ }
3783
+
3784
+ // src/application/use-cases/list-transfers.ts
3785
+ async function listTransfers(deps, query) {
3786
+ deps.logger.info("use-case: listTransfers", {
3787
+ provider: deps.provider.id
3788
+ });
3789
+ return deps.provider.listTransfers(query);
3790
+ }
3791
+
3792
+ // src/application/services/transfer-service.ts
3793
+ var TransferService = class {
3794
+ constructor(provider, eventBus, logger, clock, idGenerator) {
3795
+ this.provider = provider;
3796
+ this.eventBus = eventBus;
3797
+ this.logger = logger;
3798
+ this.clock = clock;
3799
+ this.idGenerator = idGenerator;
3800
+ }
3801
+ provider;
3802
+ eventBus;
3803
+ logger;
3804
+ clock;
3805
+ idGenerator;
3806
+ async listBankCodes(currency, options = {}) {
3807
+ return listBankCodes(
3808
+ { provider: this.provider, logger: this.logger },
3809
+ currency,
3810
+ options
3811
+ );
3812
+ }
3813
+ async resolveAccount(input) {
3814
+ return resolveAccount(
3815
+ { provider: this.provider, logger: this.logger },
3816
+ input
3817
+ );
3818
+ }
3819
+ async createRecipient(input) {
3820
+ return createRecipient(
3821
+ { provider: this.provider, logger: this.logger, clock: this.clock },
3822
+ input
3823
+ );
3824
+ }
3825
+ /**
3826
+ * Locks an exchange rate for a cross-currency payout. Pass the returned id
3827
+ * as `quoteId` to {@link initiate} (and omit `amount`).
3828
+ */
3829
+ async createQuote(input) {
3830
+ return createTransferQuote(
3831
+ { provider: this.provider, logger: this.logger },
3832
+ input
3833
+ );
3834
+ }
3835
+ async initiate(input) {
3836
+ return initiateTransfer(
3837
+ {
3838
+ provider: this.provider,
3839
+ eventBus: this.eventBus,
3840
+ logger: this.logger,
3841
+ clock: this.clock,
3842
+ idGenerator: this.idGenerator
3843
+ },
3844
+ input
3845
+ );
3846
+ }
3847
+ async fetch(id) {
3848
+ return fetchTransfer(
3849
+ { provider: this.provider, logger: this.logger },
3850
+ id
3851
+ );
3852
+ }
3853
+ async list(query) {
3854
+ return listTransfers(
3855
+ { provider: this.provider, logger: this.logger },
3856
+ query
3857
+ );
3858
+ }
3859
+ };
3860
+
3861
+ // src/application/services/subscription-facade-deps.ts
3862
+ function unsupportedProviderError(providerId, feature) {
3863
+ return new UnsupportedProviderError(
3864
+ `Provider "${providerId}" does not support ${feature}. Configure a provider that implements the subscription capability (Bachs does).`,
3865
+ { provider: providerId }
3866
+ );
3867
+ }
3868
+
3869
+ // src/application/services/product-service.ts
3870
+ var ProductService = class {
3871
+ providerId;
3872
+ products;
3873
+ logger;
3874
+ constructor(deps) {
3875
+ this.providerId = deps.providerId;
3876
+ this.products = deps.subscriptionProvider;
3877
+ this.logger = deps.logger;
3878
+ }
3879
+ async list(query = {}) {
3880
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3881
+ this.logger.info("listing products", { provider: this.providerId, ...query });
3882
+ return this.products.listProducts(query);
3883
+ }
3884
+ async fetch(id) {
3885
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3886
+ this.logger.info("fetching product", { provider: this.providerId, productId: id });
3887
+ return this.products.fetchProduct(id);
3888
+ }
3889
+ async create(input) {
3890
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3891
+ this.logger.info("creating product", {
3892
+ provider: this.providerId,
3893
+ recurring: input.billingCycle !== void 0
3894
+ });
3895
+ return this.products.createProduct(input);
3896
+ }
3897
+ async update(id, input) {
3898
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3899
+ this.logger.info("updating product", { provider: this.providerId, productId: id });
3900
+ return this.products.updateProduct(id, input);
3901
+ }
3902
+ /** Archived products stop selling but keep billing existing subscriptions. */
3903
+ async archive(id) {
3904
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3905
+ this.logger.info("archiving product", { provider: this.providerId, productId: id });
3906
+ return this.products.archiveProduct(id);
3907
+ }
3908
+ async unarchive(id) {
3909
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3910
+ this.logger.info("unarchiving product", { provider: this.providerId, productId: id });
3911
+ return this.products.unarchiveProduct(id);
3912
+ }
3913
+ };
3914
+
3915
+ // src/application/services/subscription-service.ts
3916
+ var SubscriptionService = class {
3917
+ providerId;
3918
+ subscriptions;
3919
+ logger;
3920
+ eventBus;
3921
+ clock;
3922
+ idGenerator;
3923
+ constructor(deps) {
3924
+ this.providerId = deps.providerId;
3925
+ this.subscriptions = deps.subscriptionProvider;
3926
+ this.logger = deps.logger;
3927
+ this.eventBus = deps.eventBus;
3928
+ this.clock = deps.clock;
3929
+ this.idGenerator = deps.idGenerator;
3930
+ }
3931
+ async list(query = {}) {
3932
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3933
+ this.logger.info("listing subscriptions", { provider: this.providerId, ...query });
3934
+ return this.subscriptions.listSubscriptions(query);
3935
+ }
3936
+ async fetch(id) {
3937
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3938
+ this.logger.info("fetching subscription", { provider: this.providerId, subscriptionId: id });
3939
+ return this.subscriptions.fetchSubscription(id);
3940
+ }
3941
+ /**
3942
+ * Applies exactly one change. Bachs rejects combined intents, so combining
3943
+ * `productId`, `trialEnd`, `paymentMethodId`, or `metadata` in one call
3944
+ * throws rather than sending a request the provider will refuse.
3945
+ *
3946
+ * Emits `subscription.updated` on success.
3947
+ */
3948
+ async update(id, input) {
3949
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3950
+ const intents = [
3951
+ input.productId !== void 0,
3952
+ input.trialEnd !== void 0,
3953
+ input.paymentMethodId !== void 0,
3954
+ input.metadata !== void 0
3955
+ ].filter(Boolean).length;
3956
+ if (intents === 0) {
3957
+ throw new ValidationError(
3958
+ "Subscription update requires exactly one intent: productId, trialEnd, paymentMethodId, or metadata"
3959
+ );
3960
+ }
3961
+ if (intents > 1) {
3962
+ throw new ValidationError(
3963
+ "Bachs accepts exactly one subscription intent per call; send productId, trialEnd, paymentMethodId, and metadata in separate calls"
3964
+ );
3965
+ }
3966
+ this.logger.info("updating subscription", { provider: this.providerId, subscriptionId: id });
3967
+ const result = await this.subscriptions.updateSubscription(id, input);
3968
+ if (result.ok) this.emit("subscription.updated", result.value);
3969
+ return result;
3970
+ }
3971
+ /**
3972
+ * Cancels immediately, or at the period end when `atPeriodEnd` is true.
3973
+ * Emits `subscription.canceled` on success.
3974
+ */
3975
+ async cancel(id, input = {}) {
3976
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3977
+ this.logger.info("canceling subscription", {
3978
+ provider: this.providerId,
3979
+ subscriptionId: id,
3980
+ atPeriodEnd: input.atPeriodEnd ?? false
3981
+ });
3982
+ const result = await this.subscriptions.cancelSubscription(id, input);
3983
+ if (result.ok) this.emit("subscription.canceled", result.value);
3984
+ return result;
3985
+ }
3986
+ emit(type, subscription) {
3987
+ if (!this.eventBus) return;
3988
+ const occurredAt = this.clock?.now() ?? /* @__PURE__ */ new Date();
3989
+ const correlationId = this.idGenerator?.generate() ?? "unknown";
3990
+ if (type === "subscription.updated") {
3991
+ this.eventBus.emit({ type: "subscription.updated", subscription, occurredAt, correlationId });
3992
+ } else {
3993
+ this.eventBus.emit({ type: "subscription.canceled", subscription, occurredAt, correlationId });
3994
+ }
3995
+ }
3996
+ };
3997
+
3998
+ // src/application/services/customer-service.ts
3999
+ var CustomerService = class {
4000
+ providerId;
4001
+ customers;
4002
+ logger;
4003
+ constructor(deps) {
4004
+ this.providerId = deps.providerId;
4005
+ this.customers = deps.subscriptionProvider;
4006
+ this.logger = deps.logger;
4007
+ }
4008
+ async list(query = {}) {
4009
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4010
+ this.logger.info("listing customers", { provider: this.providerId, ...query });
4011
+ return this.customers.listCustomers(query);
4012
+ }
4013
+ async fetch(id) {
4014
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4015
+ this.logger.info("fetching customer", { provider: this.providerId, customerId: id });
4016
+ return this.customers.fetchCustomer(id);
4017
+ }
4018
+ async create(input) {
4019
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4020
+ this.logger.info("creating customer", { provider: this.providerId });
4021
+ return this.customers.createCustomer(input);
4022
+ }
4023
+ async update(id, input) {
4024
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4025
+ this.logger.info("updating customer", { provider: this.providerId, customerId: id });
4026
+ return this.customers.updateCustomer(id, input);
4027
+ }
4028
+ /**
4029
+ * Mints a short-lived, pre-authenticated portal URL for one customer.
4030
+ *
4031
+ * The URL is a credential. It is deliberately not logged, and callers must
4032
+ * not cache or persist it — mint a fresh session per request.
4033
+ */
4034
+ async createPortalSession(customerId) {
4035
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "the customer portal"));
4036
+ this.logger.info("creating customer portal session", {
4037
+ provider: this.providerId,
4038
+ customerId
4039
+ });
4040
+ return this.customers.createPortalSession(customerId);
4041
+ }
4042
+ };
4043
+
4044
+ // src/application/ports/subscription-provider.ts
4045
+ function isSubscriptionProvider(value) {
4046
+ const candidate = value;
4047
+ return typeof candidate?.listSubscriptions === "function" && typeof candidate.createProduct === "function";
4048
+ }
4049
+
4050
+ // src/application/services/provider-registry.ts
4051
+ var ProviderRegistry = class {
4052
+ constructor(factory, providers, logger) {
4053
+ this.factory = factory;
4054
+ this.providers = providers;
4055
+ this.logger = logger;
4056
+ }
4057
+ factory;
4058
+ providers;
4059
+ logger;
4060
+ get(id) {
4061
+ const provider = id;
4062
+ const instance = this.providers.get(provider);
4063
+ if (!instance) {
4064
+ const available = [...this.providers.keys()].join(", ") || "none";
4065
+ throw new ConfigurationError(
4066
+ `Unknown provider "${id}". Available: ${available}`
4067
+ );
4068
+ }
4069
+ return instance;
4070
+ }
4071
+ list() {
4072
+ return this.factory.supported();
4073
+ }
4074
+ capabilities(id) {
4075
+ return this.get(id).capabilities;
4076
+ }
4077
+ async health(id) {
4078
+ return this.get(id).health();
4079
+ }
4080
+ };
4081
+
4082
+ // src/application/services/event-subscription-view.ts
4083
+ var EventSubscriptionView = class {
4084
+ constructor(bus) {
4085
+ this.bus = bus;
4086
+ }
4087
+ bus;
4088
+ on(type, handler) {
4089
+ return this.bus.on(type, handler);
4090
+ }
4091
+ onAny(handler) {
4092
+ return this.bus.onAny(handler);
4093
+ }
4094
+ };
4095
+
4096
+ // src/infrastructure/http/retry-policy.ts
4097
+ var DEFAULT_RETRY_DELAY_MS = 500;
4098
+ var RETRY_JITTER_MS = 250;
4099
+ var MAX_RETRY_AFTER_MS = 1e4;
4100
+ function parseRetryAfterMs(header, nowMs) {
4101
+ if (header === void 0) return void 0;
4102
+ const trimmed = header.trim();
4103
+ if (trimmed.length === 0) return void 0;
4104
+ if (/^\d+$/.test(trimmed)) {
4105
+ return Number(trimmed) * 1e3;
4106
+ }
4107
+ const date = new Date(trimmed);
4108
+ if (Number.isNaN(date.getTime()) || !/[A-Za-z]/.test(trimmed)) return void 0;
4109
+ return Math.max(0, date.getTime() - nowMs);
4110
+ }
4111
+ function computeRetryDelayMs(input = {}) {
4112
+ const base = input.baseDelayMs ?? DEFAULT_RETRY_DELAY_MS;
4113
+ const jitter = input.jitterMs ?? RETRY_JITTER_MS;
4114
+ const max = input.maxDelayMs ?? MAX_RETRY_AFTER_MS;
4115
+ const random = input.random ?? Math.random;
4116
+ const candidate = input.retryAfterMs !== void 0 ? input.retryAfterMs : base + Math.floor(random() * jitter);
4117
+ return Math.min(Math.max(candidate, 0), max);
4118
+ }
4119
+
4120
+ // src/infrastructure/http/fetch-http-client.ts
4121
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
4122
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
4123
+ var DEFAULT_MAX_RETRIES = 1;
4124
+ var FetchHttpClient = class {
4125
+ baseUrl;
4126
+ defaultTimeoutMs;
4127
+ maxRetries;
4128
+ retryBaseDelayMs;
4129
+ correlationId;
4130
+ provider;
4131
+ logger;
4132
+ constructor(config = {}) {
4133
+ this.baseUrl = config.baseUrl;
4134
+ this.defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS2;
4135
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
4136
+ this.retryBaseDelayMs = config.retryBaseDelayMs;
4137
+ this.correlationId = config.correlationId;
4138
+ this.provider = config.provider;
4139
+ this.logger = config.logger;
4140
+ }
4141
+ async send(request) {
4142
+ const builtUrl = this.tryBuildUrl(request.url);
4143
+ if (!builtUrl.ok) return builtUrl;
4144
+ const url = builtUrl.value;
4145
+ const timeoutMs = request.timeoutMs ?? this.defaultTimeoutMs;
4146
+ const isRetryable = request.isRetryable ?? IDEMPOTENT_METHODS.has(request.method);
4147
+ let lastError;
4148
+ const maxAttempts = isRetryable ? 1 + this.maxRetries : 1;
4149
+ for (let attempt2 = 0; attempt2 < maxAttempts; attempt2++) {
4150
+ if (attempt2 > 0) {
4151
+ const delayMs = computeRetryDelayMs({
4152
+ retryAfterMs: retryAfterFromError(lastError),
4153
+ baseDelayMs: this.retryBaseDelayMs
4154
+ });
4155
+ this.logger?.debug("retrying HTTP request", {
4156
+ method: request.method,
4157
+ url,
4158
+ attempt: String(attempt2),
4159
+ delayMs
4160
+ });
4161
+ await sleep(delayMs);
4162
+ }
4163
+ const result = await this.attempt(request, url, timeoutMs, attempt2);
4164
+ if (result.ok) return result;
4165
+ lastError = result.error;
4166
+ if (!isRetryable || !isRetryableError(lastError)) {
4167
+ return result;
4168
+ }
4169
+ }
4170
+ this.logger?.error("HTTP request failed after retries", lastError, {
4171
+ method: request.method,
4172
+ url
4173
+ });
4174
+ return err(lastError);
4175
+ }
4176
+ async attempt(request, url, timeoutMs, _attempt) {
4177
+ const controller = new AbortController();
4178
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4179
+ try {
4180
+ const headers = {
4181
+ "Content-Type": "application/json",
4182
+ Accept: "application/json",
4183
+ ...request.headers
4184
+ };
4185
+ if (request.correlationId) {
4186
+ headers["X-TEC-Correlation-Id"] = request.correlationId;
4187
+ }
4188
+ if (request.idempotencyKey) {
4189
+ headers["Idempotency-Key"] = request.idempotencyKey;
4190
+ }
4191
+ const response = await fetch(url, {
4192
+ method: request.method,
4193
+ headers,
4194
+ body: request.body,
4195
+ signal: controller.signal,
4196
+ // API endpoints must not redirect: a 30x can point at http:// (breaking
4197
+ // the HTTPS-only rule) or at another origin. Surface it as an error.
4198
+ redirect: "manual"
4199
+ });
4200
+ const body = await response.text();
4201
+ if (response.status >= 300 && response.status < 400) {
4202
+ return err(new ProviderError(
4203
+ `Provider responded with a redirect (${response.status}); redirects are not followed`,
4204
+ {
4205
+ provider: this.provider,
4206
+ providerCode: String(response.status),
4207
+ httpStatus: response.status,
4208
+ isRetryable: false,
4209
+ meta: { url, status: response.status }
4210
+ }
4211
+ ));
4212
+ }
4213
+ if (!response.ok) {
4214
+ return this.mapError(response.status, body, url, response.headers);
4215
+ }
4216
+ const respHeaders = {};
4217
+ response.headers.forEach((value, key) => {
4218
+ respHeaders[key] = value;
4219
+ });
4220
+ return ok({
4221
+ status: response.status,
4222
+ headers: respHeaders,
4223
+ body
4224
+ });
4225
+ } catch (e) {
4226
+ if (isAbortError(e)) {
4227
+ return err(new TimeoutError(`Request to ${url} timed out after ${timeoutMs}ms`, {
4228
+ provider: this.provider,
4229
+ meta: { url, timeoutMs }
4230
+ }));
4231
+ }
4232
+ const message = e instanceof Error ? e.message : String(e);
4233
+ return err(new NetworkError(`Network error for ${url}: ${message}`, {
4234
+ provider: this.provider,
4235
+ meta: { url },
4236
+ cause: e instanceof Error ? e : void 0
4237
+ }));
4238
+ } finally {
4239
+ clearTimeout(timer);
4240
+ }
4241
+ }
4242
+ /**
4243
+ * Resolves the request URL, reporting an insecure one as a `Result` rather
4244
+ * than throwing out of `send`. `createPaymentClient` already rejects insecure
4245
+ * base URLs at construction; this is the last line of defence for URLs built
4246
+ * by an adapter.
4247
+ */
4248
+ tryBuildUrl(pathOrUrl) {
4249
+ const resolved = pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://") ? pathOrUrl : this.baseUrl ? `${this.baseUrl.replace(/\/$/, "")}/${pathOrUrl.replace(/^\//, "")}` : pathOrUrl;
4250
+ if (resolved.startsWith("http://")) {
4251
+ return err(new NetworkError(`HTTP URLs are not allowed: ${resolved}`, {
4252
+ provider: this.provider,
4253
+ meta: { url: resolved }
4254
+ }));
4255
+ }
4256
+ return ok(resolved);
4257
+ }
4258
+ mapError(status, body, url, headers) {
4259
+ const meta = { url, status, body: body.slice(0, 500) };
4260
+ const retryAfterMs = parseRetryAfterMs(headers.get("retry-after") ?? void 0, Date.now());
4261
+ if (retryAfterMs !== void 0 && (status === 429 || status >= 500)) {
4262
+ meta["retryAfterMs"] = retryAfterMs;
4263
+ }
4264
+ if (status >= 500) {
4265
+ return err(new ProviderUnavailableError(
4266
+ `Provider returned ${status} for ${url}`,
4267
+ {
4268
+ provider: this.provider,
4269
+ providerCode: String(status),
4270
+ meta
4271
+ }
4272
+ ));
4273
+ }
4274
+ if (status === 429) {
4275
+ return err(new ProviderRateLimitError(
4276
+ `Rate limited (${status}) by provider`,
4277
+ {
4278
+ provider: this.provider,
4279
+ providerCode: String(status),
4280
+ meta
4281
+ }
4282
+ ));
4283
+ }
4284
+ if (status === 400) {
4285
+ return err(new ProviderBadRequestError(
4286
+ `Bad request (${status}) to provider`,
4287
+ {
4288
+ provider: this.provider,
4289
+ providerCode: String(status),
4290
+ meta
4291
+ }
4292
+ ));
4293
+ }
4294
+ if (status === 401 || status === 403) {
4295
+ return err(new ProviderUnauthorizedError(
4296
+ `Unauthorized (${status}) to provider`,
4297
+ {
4298
+ provider: this.provider,
4299
+ providerCode: String(status),
4300
+ httpStatus: status,
4301
+ meta
4302
+ }
4303
+ ));
4304
+ }
4305
+ if (status === 404) {
4306
+ return err(new ProviderNotFoundError(
4307
+ `Not found (${status}) at provider`,
4308
+ {
4309
+ provider: this.provider,
4310
+ providerCode: String(status),
4311
+ meta
4312
+ }
4313
+ ));
4314
+ }
4315
+ if (status === 409) {
4316
+ return err(new ProviderConflictError(
4317
+ `Conflict (${status}) at provider`,
4318
+ {
4319
+ provider: this.provider,
4320
+ providerCode: String(status),
4321
+ meta
4322
+ }
4323
+ ));
4324
+ }
4325
+ return err(new ProviderError(
4326
+ `Provider returned error ${status}`,
4327
+ {
4328
+ provider: this.provider,
4329
+ providerCode: String(status),
4330
+ httpStatus: status,
4331
+ isRetryable: false,
4332
+ meta
4333
+ }
4334
+ ));
4335
+ }
4336
+ };
4337
+ function isAbortError(e) {
4338
+ if (e instanceof Error && e.name === "AbortError") return true;
4339
+ return false;
4340
+ }
4341
+ function retryAfterFromError(error) {
4342
+ const value = error?.meta?.["retryAfterMs"];
4343
+ return typeof value === "number" ? value : void 0;
4344
+ }
4345
+ function isRetryableError(error) {
4346
+ if (error.isRetryable) return true;
4347
+ if (error instanceof ProviderUnavailableError) return true;
4348
+ if (error instanceof ProviderRateLimitError) return true;
4349
+ if (error instanceof NetworkError) return true;
4350
+ if (error instanceof TimeoutError) return true;
4351
+ return false;
4352
+ }
4353
+ function sleep(ms) {
4354
+ return new Promise((resolve) => setTimeout(resolve, ms));
4355
+ }
4356
+
4357
+ // src/infrastructure/logging/console-logger.ts
4358
+ var SENSITIVE_RE = /(secret|authorization|password|signature|api[_-]?key|card|pan|cvv)/i;
4359
+ var REPLACEMENT = "[REDACTED]";
4360
+ function redactValue(value) {
4361
+ if (Array.isArray(value)) {
4362
+ return value.map(redactValue);
4363
+ }
4364
+ if (value !== null && typeof value === "object") {
4365
+ return redact(value);
4366
+ }
4367
+ return value;
4368
+ }
4369
+ function redact(obj) {
4370
+ const result = {};
4371
+ for (const key of Object.keys(obj)) {
4372
+ const value = obj[key];
4373
+ if (SENSITIVE_RE.test(key)) {
4374
+ result[key] = REPLACEMENT;
4375
+ } else {
4376
+ result[key] = redactValue(value);
4377
+ }
4378
+ }
4379
+ return result;
4380
+ }
4381
+ function formatJson(entry) {
4382
+ try {
4383
+ return JSON.stringify(redact(entry));
4384
+ } catch {
4385
+ return JSON.stringify({ message: "log serialization error" });
4386
+ }
4387
+ }
4388
+ var ConsoleLogger = class _ConsoleLogger {
4389
+ bindings;
4390
+ constructor(bindings = {}) {
4391
+ this.bindings = bindings;
4392
+ }
4393
+ debug(message, context) {
4394
+ console.log(formatJson({ level: "debug", message, ...this.bindings, ...context }));
4395
+ }
4396
+ info(message, context) {
4397
+ console.log(formatJson({ level: "info", message, ...this.bindings, ...context }));
4398
+ }
4399
+ warn(message, context) {
4400
+ console.warn(formatJson({ level: "warn", message, ...this.bindings, ...context }));
4401
+ }
4402
+ error(message, error, context) {
4403
+ const errObj = { level: "error", message, ...this.bindings, ...context };
4404
+ if (error instanceof Error) {
4405
+ errObj.error = { name: error.name, message: error.message };
4406
+ } else if (error !== void 0) {
4407
+ errObj.error = String(error);
4408
+ }
4409
+ console.error(formatJson(errObj));
4410
+ }
4411
+ child(bindings) {
4412
+ return new _ConsoleLogger({ ...this.bindings, ...bindings });
4413
+ }
4414
+ };
4415
+
4416
+ // src/infrastructure/logging/noop-logger.ts
4417
+ var NoopLogger = class {
4418
+ debug(_message, _context) {
4419
+ }
4420
+ info(_message, _context) {
4421
+ }
4422
+ warn(_message, _context) {
4423
+ }
4424
+ error(_message, _error, _context) {
4425
+ }
4426
+ child(_bindings) {
4427
+ return this;
4428
+ }
4429
+ };
4430
+
4431
+ // src/infrastructure/clock/system-clock.ts
4432
+ var SystemClock = class {
4433
+ now() {
4434
+ return /* @__PURE__ */ new Date();
4435
+ }
4436
+ };
4437
+ var UlidIdGenerator = class {
4438
+ generate() {
4439
+ return randomUUID();
4440
+ }
4441
+ };
4442
+
4443
+ // src/infrastructure/event-bus/in-memory-event-bus.ts
4444
+ var InMemoryEventBus = class {
4445
+ subscriptions = [];
4446
+ logger;
4447
+ dispatching = false;
4448
+ pending = [];
4449
+ constructor(logger) {
4450
+ this.logger = logger;
4451
+ }
4452
+ emit(event) {
4453
+ if (this.dispatching) {
4454
+ this.pending.push(event);
4455
+ return;
4456
+ }
4457
+ this.dispatching = true;
4458
+ try {
4459
+ this.dispatch(event);
4460
+ } finally {
4461
+ this.dispatching = false;
4462
+ while (this.pending.length > 0) {
4463
+ const next = this.pending.shift();
4464
+ this.emit(next);
4465
+ }
4466
+ }
4467
+ }
4468
+ on(type, handler) {
4469
+ const sub = { type, handler };
4470
+ this.subscriptions.push(sub);
4471
+ return () => {
4472
+ const idx = this.subscriptions.indexOf(sub);
4473
+ if (idx >= 0) this.subscriptions.splice(idx, 1);
4474
+ };
4475
+ }
4476
+ onAny(handler) {
4477
+ const sub = { type: "*", handler };
4478
+ this.subscriptions.push(sub);
4479
+ return () => {
4480
+ const idx = this.subscriptions.indexOf(sub);
4481
+ if (idx >= 0) this.subscriptions.splice(idx, 1);
4482
+ };
4483
+ }
4484
+ dispatch(event) {
4485
+ for (const sub of [...this.subscriptions]) {
4486
+ if (sub.type !== "*" && sub.type !== event.type) continue;
4487
+ try {
4488
+ const result = sub.handler(event);
4489
+ if (result instanceof Promise) {
4490
+ result.catch((err2) => {
4491
+ this.logger.error("event handler rejected", err2, {
4492
+ eventType: event.type,
4493
+ correlationId: event.correlationId
4494
+ });
4495
+ });
4496
+ }
4497
+ } catch (err2) {
4498
+ this.logger.error("event handler threw", err2 instanceof Error ? err2 : void 0, {
4499
+ eventType: event.type,
4500
+ correlationId: event.correlationId
4501
+ });
4502
+ }
4503
+ }
4504
+ }
4505
+ };
4506
+
4507
+ // src/public-api/client.ts
4508
+ function createLogger(config) {
4509
+ if (config.logger) return config.logger;
4510
+ if (config.logging?.level === "debug") {
4511
+ return new ConsoleLogger({ provider: "tec-payment" });
4512
+ }
4513
+ return new NoopLogger();
4514
+ }
4515
+ function resolveRetryConfig(config) {
4516
+ const maxRetries = config.retry?.maxRetries;
4517
+ const delayMs = config.retry?.delayMs;
4518
+ if (maxRetries !== void 0 && (!Number.isInteger(maxRetries) || maxRetries < 0)) {
4519
+ throw new ConfigurationError(
4520
+ `retry.maxRetries must be a non-negative integer, got ${String(maxRetries)}`
4521
+ );
4522
+ }
4523
+ if (delayMs !== void 0 && (!Number.isFinite(delayMs) || delayMs < 0)) {
4524
+ throw new ConfigurationError(
4525
+ `retry.delayMs must be a non-negative number, got ${String(delayMs)}`
4526
+ );
4527
+ }
4528
+ return { maxRetries: maxRetries ?? 1, delayMs };
4529
+ }
4530
+ function resolveHttpConfig(config) {
4531
+ const timeoutMs = config.http?.timeoutMs;
4532
+ if (timeoutMs !== void 0 && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
4533
+ throw new ConfigurationError(
4534
+ `http.timeoutMs must be a positive integer, got ${String(timeoutMs)}`
4535
+ );
4536
+ }
4537
+ return { timeoutMs, baseUrl: config.http?.baseUrl };
4538
+ }
4539
+ function assertSecureBaseUrl(providerId, baseUrl, allowInsecure) {
4540
+ if (!baseUrl || !baseUrl.startsWith("http://")) return;
4541
+ if (allowInsecure) return;
4542
+ throw new ConfigurationError(
4543
+ `Provider "${providerId}" is configured with an insecure base URL (${baseUrl}). Set allowInsecureBaseUrl: true on that provider to use it (tests and local stubs only), or use an https URL.`
4544
+ );
4545
+ }
4546
+ function createPaymentClient(config) {
4547
+ const logger = createLogger(config);
4548
+ if (!config.providers || Object.keys(config.providers).length === 0) {
4549
+ throw new ConfigurationError("At least one provider must be configured");
4550
+ }
4551
+ const retry = resolveRetryConfig(config);
4552
+ const httpDefaults = resolveHttpConfig(config);
4553
+ const clock = config.clock ?? new SystemClock();
4554
+ const idGenerator = config.idGenerator ?? new UlidIdGenerator();
4555
+ const eventBus = config.eventBus ?? new InMemoryEventBus(
4556
+ logger.child({ component: "event-bus" })
4557
+ );
4558
+ const providerFactory = createProviderFactory();
4559
+ const providerMap = /* @__PURE__ */ new Map();
4560
+ for (const [providerId, providerConfig] of Object.entries(config.providers)) {
4561
+ if (!providerConfig || providerConfig.enabled === false) continue;
4562
+ const baseUrl = providerConfig.baseUrl ?? httpDefaults.baseUrl;
4563
+ assertSecureBaseUrl(providerId, baseUrl, providerConfig.allowInsecureBaseUrl);
4564
+ const httpClient = config.httpClient ?? new FetchHttpClient({
4565
+ baseUrl,
4566
+ defaultTimeoutMs: providerConfig.timeoutMs ?? httpDefaults.timeoutMs,
4567
+ maxRetries: retry.maxRetries,
4568
+ retryBaseDelayMs: retry.delayMs,
4569
+ provider: providerId,
4570
+ logger: logger.child({ provider: providerId })
4571
+ });
4572
+ const webhookSecret = providerConfig.webhookSecret ?? providerConfig.secretKey;
4573
+ const webhookVerifier = new HmacWebhookVerifier(webhookSecret, "sha512");
4574
+ const provider = providerFactory.create(providerId, providerConfig, {
4575
+ httpClient,
4576
+ logger: logger.child({ provider: providerId }),
4577
+ clock,
4578
+ idGenerator,
4579
+ eventBus,
4580
+ webhookVerifier
4581
+ });
4582
+ providerMap.set(providerId, provider);
4583
+ }
4584
+ if (providerMap.size === 0) {
4585
+ throw new ConfigurationError("No providers are enabled. Check your configuration.");
4586
+ }
4587
+ const defaultProviderId = config.defaultProvider ? config.defaultProvider : providerMap.keys().next().value;
4588
+ if (!providerMap.has(defaultProviderId)) {
4589
+ throw new ConfigurationError(
4590
+ `Default provider "${config.defaultProvider}" is not configured or enabled.`
4591
+ );
4592
+ }
4593
+ const defaultProvider = providerMap.get(defaultProviderId);
4594
+ const providers = new ProviderRegistry(providerFactory, providerMap, logger);
4595
+ const payments = new PaymentService(
4596
+ defaultProvider,
4597
+ eventBus,
4598
+ logger.child({ component: "payment-service" }),
4599
+ clock,
4600
+ idGenerator
4601
+ );
4602
+ const serviceDeps = {
4603
+ eventBus,
4604
+ logger,
4605
+ clock,
4606
+ idGenerator
4607
+ };
4608
+ const refunds = new RefundService(defaultProvider, serviceDeps);
4609
+ const webhooks = new WebhookService(providerMap, serviceDeps);
4610
+ const transferDeps = {
4611
+ eventBus,
4612
+ logger: logger.child({ component: "transfer-service" }),
4613
+ clock,
4614
+ idGenerator
4615
+ };
4616
+ const transfers = new TransferService(defaultProvider, transferDeps.eventBus, transferDeps.logger, transferDeps.clock, transferDeps.idGenerator);
4617
+ const subscriptionProvider = isSubscriptionProvider(defaultProvider) ? defaultProvider : void 0;
4618
+ const catalogDeps = {
4619
+ providerId: defaultProviderId,
4620
+ subscriptionProvider,
4621
+ logger: logger.child({ component: "product-service" })
4622
+ };
4623
+ const products = new ProductService(catalogDeps);
4624
+ const subscriptions = new SubscriptionService({
4625
+ ...catalogDeps,
4626
+ logger: logger.child({ component: "subscription-service" }),
4627
+ eventBus,
4628
+ clock,
4629
+ idGenerator
4630
+ });
4631
+ const customers = new CustomerService({
4632
+ ...catalogDeps,
4633
+ logger: logger.child({ component: "customer-service" })
4634
+ });
4635
+ const events = new EventSubscriptionView(eventBus);
4636
+ return {
4637
+ payments,
4638
+ refunds,
4639
+ webhooks,
4640
+ transfers,
4641
+ products,
4642
+ subscriptions,
4643
+ customers,
4644
+ events,
4645
+ providers,
4646
+ async health() {
4647
+ const results = [];
4648
+ for (const [_id, provider] of providerMap) {
4649
+ try {
4650
+ results.push(await provider.health());
4651
+ } catch {
4652
+ results.push({
4653
+ healthy: false,
4654
+ latencyMs: 0,
4655
+ timestamp: clock.now()
4656
+ });
4657
+ }
4658
+ }
4659
+ return results;
4660
+ }
4661
+ };
4662
+ }
4663
+ function createClientFromEnv() {
4664
+ const defaultProvider = process.env.TEC_PAYMENT_DEFAULT_PROVIDER ?? "paystack";
4665
+ const logLevel = process.env.TEC_PAYMENT_LOGGING_LEVEL ?? "info";
4666
+ const providers = {};
4667
+ const paystackKey = process.env.TEC_PAYMENT_PAYSTACK_SECRET_KEY ?? process.env.PAYSTACK_SECRET_KEY;
4668
+ if (paystackKey) {
4669
+ providers.paystack = {
4670
+ secretKey: paystackKey,
4671
+ webhookSecret: process.env.TEC_PAYMENT_PAYSTACK_WEBHOOK_SECRET ?? process.env.PAYSTACK_WEBHOOK_SECRET,
4672
+ baseUrl: process.env.TEC_PAYMENT_PAYSTACK_BASE_URL ?? process.env.PAYSTACK_BASE_URL
4673
+ };
4674
+ }
4675
+ const bachsKey = process.env.TEC_PAYMENT_BACHS_SECRET_KEY ?? process.env.BACHS_SECRET_KEY;
4676
+ if (bachsKey) {
4677
+ providers.bachs = {
4678
+ secretKey: bachsKey,
4679
+ // Bachs signs webhooks with the endpoint signing secret (whsec_...),
4680
+ // never with the API key, so there is no fallback here.
4681
+ webhookSecret: process.env.TEC_PAYMENT_BACHS_WEBHOOK_SECRET ?? process.env.BACHS_WEBHOOK_SECRET,
4682
+ baseUrl: process.env.TEC_PAYMENT_BACHS_BASE_URL ?? process.env.BACHS_BASE_URL,
4683
+ timeoutMs: process.env.TEC_PAYMENT_BACHS_TIMEOUT_MS ? Number(process.env.TEC_PAYMENT_BACHS_TIMEOUT_MS) : void 0
4684
+ };
4685
+ }
4686
+ return createPaymentClient({
4687
+ providers,
4688
+ defaultProvider,
4689
+ logging: { level: logLevel }
4690
+ });
4691
+ }
4692
+ createPaymentClient.fromEnv = createClientFromEnv;
4693
+
4694
+ // src/domain/payment/payment-status.ts
4695
+ function isFinalStatus(status) {
4696
+ return status.kind === "success" || status.kind === "failed" || status.kind === "refunded";
4697
+ }
4698
+ function isTransitionAllowed(from, to) {
4699
+ const allowed = {
4700
+ initialized: /* @__PURE__ */ new Set(["pending", "failed", "abandoned"]),
4701
+ pending: /* @__PURE__ */ new Set(["success", "failed", "abandoned"]),
4702
+ success: /* @__PURE__ */ new Set(["refunded"]),
4703
+ failed: /* @__PURE__ */ new Set([]),
4704
+ abandoned: /* @__PURE__ */ new Set([]),
4705
+ refunded: /* @__PURE__ */ new Set([])
4706
+ };
4707
+ return allowed[from]?.has(to) ?? false;
4708
+ }
4709
+
4710
+ // src/domain/product/product.ts
4711
+ function isRecurring(product) {
4712
+ return product.billingCycle !== void 0;
4713
+ }
4714
+
4715
+ // src/domain/subscription/subscription-status.ts
4716
+ function isFinalSubscriptionStatus(status) {
4717
+ return status.kind === "canceled";
4718
+ }
4719
+ function isSubscriptionActive(status) {
4720
+ return status.kind === "active" || status.kind === "trialing";
4721
+ }
4722
+ function isSubscriptionDelinquent(status) {
4723
+ return status.kind === "pastDue" || status.kind === "unpaid";
4724
+ }
4725
+
4726
+ // src/domain/refund/refund-status.ts
4727
+ function isFinalRefundStatus(status) {
4728
+ return status.kind === "succeeded" || status.kind === "failed";
4729
+ }
4730
+
4731
+ // src/domain/refund/refund-reason.ts
4732
+ function RefundReason(value) {
4733
+ return value.trim().toLowerCase();
4734
+ }
4735
+
4736
+ // src/domain/transfer/transfer-status.ts
4737
+ function isFinalTransferStatus(status) {
4738
+ return status.kind === "succeeded" || status.kind === "failed" || status.kind === "reversed";
4739
+ }
4740
+
4741
+ // src/infrastructure/http/mock-http-client.ts
4742
+ var MockHttpClient = class {
4743
+ responses = /* @__PURE__ */ new Map();
4744
+ requests = [];
4745
+ on(method, urlMatch, response) {
4746
+ this.responses.set(`${method}:${urlMatch}`, response);
4747
+ return this;
4748
+ }
4749
+ getRequests() {
4750
+ return this.requests;
4751
+ }
4752
+ clearRequests() {
4753
+ this.requests = [];
4754
+ }
4755
+ reset() {
4756
+ this.requests = [];
4757
+ this.responses.clear();
4758
+ }
4759
+ async send(request) {
4760
+ this.requests.push(request);
4761
+ const exactKey = `${request.method}:${request.url}`;
4762
+ const exactMatch = this.responses.get(exactKey);
4763
+ if (exactMatch) {
4764
+ return this.buildResponse(exactMatch);
4765
+ }
4766
+ for (const [storedKey, response] of this.responses.entries()) {
4767
+ const separator = storedKey.indexOf(":");
4768
+ const urlPattern = separator >= 0 ? storedKey.slice(separator + 1) : "";
4769
+ if (urlPattern && request.url.includes(urlPattern)) {
4770
+ return this.buildResponse(response);
4771
+ }
4772
+ }
4773
+ return err(new ProviderError(`No mock response for ${exactKey}`, {
4774
+ httpStatus: 500,
4775
+ isRetryable: false
4776
+ }));
4777
+ }
4778
+ buildResponse(response) {
4779
+ if (response.status >= 400) {
4780
+ return err(new ProviderError(`HTTP ${response.status}`, {
4781
+ httpStatus: response.status,
4782
+ isRetryable: response.status >= 500
4783
+ }));
4784
+ }
4785
+ return ok({
4786
+ status: response.status,
4787
+ headers: response.headers ?? { "content-type": "application/json" },
4788
+ body: response.body
4789
+ });
4790
+ }
4791
+ };
4792
+
4793
+ // src/public-api/mock.ts
4794
+ var MOCK_BASE_URLS = {
4795
+ paystack: "https://api.paystack.co",
4796
+ bachs: "https://sandbox-api.bachs.io"
4797
+ };
4798
+ function createMockClient(options) {
4799
+ const http = new MockHttpClient();
4800
+ const webhookSecret = options?.webhookSecret ?? "whsec_mock";
4801
+ const providerId = options?.provider ?? "paystack";
4802
+ const config = {
4803
+ providers: {
4804
+ [providerId]: {
4805
+ secretKey: "sk_mock",
4806
+ webhookSecret,
4807
+ // The mock intercepts every request, but the recorded URLs (and any
4808
+ // assertion on them) have to name the provider actually under test.
4809
+ baseUrl: MOCK_BASE_URLS[providerId] ?? MOCK_BASE_URLS["paystack"],
4810
+ timeoutMs: 5e3
4811
+ }
4812
+ },
4813
+ defaultProvider: providerId,
4814
+ httpClient: http
4815
+ };
4816
+ const client = createPaymentClient(config);
4817
+ return { client, http };
4818
+ }
4819
+
4820
+ export { ConfigurationError, Currency, ErrorCategory, ErrorCode, InternalError, MinorUnits, MockHttpClient, Money, NetworkError, PaymentError, PaymentReference, Provider, ProviderBadRequestError, ProviderConflictError, ProviderError, ProviderNotFoundError, ProviderRateLimitError, ProviderUnauthorizedError, ProviderUnavailableError, RecurringCadence, RefundError, RefundReason, TimeoutError, UnsupportedProviderError, VERSION, ValidationError, VerificationError, WebhookValidationError, attempt, createMockClient, createPaymentClient, err, isFinalRefundStatus, isFinalStatus, isFinalSubscriptionStatus, isFinalTransferStatus, isRecurring, isSubscriptionActive, isSubscriptionDelinquent, isSubscriptionProvider, isTransitionAllowed, ok };
4821
+ //# sourceMappingURL=index.js.map
4822
+ //# sourceMappingURL=index.js.map