@nehorai/payments 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/dist/config/index.cjs +116 -0
  3. package/dist/config/index.cjs.map +1 -0
  4. package/dist/config/index.d.cts +125 -0
  5. package/dist/config/index.d.ts +125 -0
  6. package/dist/config/index.js +83 -0
  7. package/dist/config/index.js.map +1 -0
  8. package/dist/factory.cjs +807 -0
  9. package/dist/factory.cjs.map +1 -0
  10. package/dist/factory.d.cts +96 -0
  11. package/dist/factory.d.ts +96 -0
  12. package/dist/factory.js +777 -0
  13. package/dist/factory.js.map +1 -0
  14. package/dist/index.cjs +1341 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +40 -0
  17. package/dist/index.d.ts +40 -0
  18. package/dist/index.js +1260 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/payment-orchestrator-CPaLmDM5.d.ts +404 -0
  21. package/dist/payment-orchestrator-Co_X6T_V.d.cts +404 -0
  22. package/dist/payment-types-68W-PlGg.d.cts +211 -0
  23. package/dist/payment-types-68W-PlGg.d.ts +211 -0
  24. package/dist/providers/interfaces/index.cjs +19 -0
  25. package/dist/providers/interfaces/index.cjs.map +1 -0
  26. package/dist/providers/interfaces/index.d.cts +80 -0
  27. package/dist/providers/interfaces/index.d.ts +80 -0
  28. package/dist/providers/interfaces/index.js +1 -0
  29. package/dist/providers/interfaces/index.js.map +1 -0
  30. package/dist/repository/interfaces/index.cjs +19 -0
  31. package/dist/repository/interfaces/index.cjs.map +1 -0
  32. package/dist/repository/interfaces/index.d.cts +556 -0
  33. package/dist/repository/interfaces/index.d.ts +556 -0
  34. package/dist/repository/interfaces/index.js +1 -0
  35. package/dist/repository/interfaces/index.js.map +1 -0
  36. package/dist/routing-engine.interface-DJzGXor9.d.cts +194 -0
  37. package/dist/routing-engine.interface-h9_GmQ4b.d.ts +194 -0
  38. package/dist/services/index.cjs +806 -0
  39. package/dist/services/index.cjs.map +1 -0
  40. package/dist/services/index.d.cts +75 -0
  41. package/dist/services/index.d.ts +75 -0
  42. package/dist/services/index.js +763 -0
  43. package/dist/services/index.js.map +1 -0
  44. package/dist/state-machine-Cu6_qKnv.d.cts +109 -0
  45. package/dist/state-machine-Cu6_qKnv.d.ts +109 -0
  46. package/dist/types/index.cjs +173 -0
  47. package/dist/types/index.cjs.map +1 -0
  48. package/dist/types/index.d.cts +127 -0
  49. package/dist/types/index.d.ts +127 -0
  50. package/dist/types/index.js +130 -0
  51. package/dist/types/index.js.map +1 -0
  52. package/dist/utils/index.cjs +167 -0
  53. package/dist/utils/index.cjs.map +1 -0
  54. package/dist/utils/index.d.cts +102 -0
  55. package/dist/utils/index.d.ts +102 -0
  56. package/dist/utils/index.js +127 -0
  57. package/dist/utils/index.js.map +1 -0
  58. package/package.json +68 -0
@@ -0,0 +1,763 @@
1
+ // src/services/payment-orchestrator.ts
2
+ import { randomUUID } from "crypto";
3
+
4
+ // src/config/payment-config.ts
5
+ function createPartialConfig(partial) {
6
+ return {
7
+ providers: partial.providers ?? {},
8
+ environment: partial.environment ?? "sandbox",
9
+ defaultCurrency: partial.defaultCurrency ?? "USD"
10
+ };
11
+ }
12
+ function getConfiguredProviders(config) {
13
+ const availability = {};
14
+ for (const [name, providerConfig] of Object.entries(config.providers)) {
15
+ availability[name] = providerConfig !== void 0 && Object.keys(providerConfig).length > 0;
16
+ }
17
+ return availability;
18
+ }
19
+
20
+ // src/services/circuit-breaker-storage.interface.ts
21
+ function createDefaultState(provider) {
22
+ return {
23
+ provider,
24
+ state: "closed",
25
+ failureCount: 0,
26
+ successCount: 0,
27
+ lastFailure: null,
28
+ openedAt: null,
29
+ nextRetryAt: null
30
+ };
31
+ }
32
+ function isCircuitOpen(state) {
33
+ return state?.state === "open";
34
+ }
35
+ function shouldAttemptHalfOpen(state) {
36
+ if (!state || state.state !== "open") return false;
37
+ if (!state.nextRetryAt) return false;
38
+ return Date.now() >= state.nextRetryAt.getTime();
39
+ }
40
+
41
+ // src/services/in-memory-storage.ts
42
+ var InMemoryCircuitBreakerStorage = class {
43
+ internalStates;
44
+ constructor() {
45
+ this.internalStates = /* @__PURE__ */ new Map();
46
+ }
47
+ async getState(provider) {
48
+ return this.internalStates.get(provider) ?? null;
49
+ }
50
+ async setState(provider, state) {
51
+ this.internalStates.set(provider, { ...state });
52
+ }
53
+ async getAllStates() {
54
+ return new Map(this.internalStates);
55
+ }
56
+ async deleteState(provider) {
57
+ this.internalStates.delete(provider);
58
+ }
59
+ async getOpenCircuits() {
60
+ const open = [];
61
+ for (const [provider, state] of this.internalStates) {
62
+ if (state.state === "open") {
63
+ open.push(provider);
64
+ }
65
+ }
66
+ return open;
67
+ }
68
+ async isHealthy() {
69
+ return true;
70
+ }
71
+ /**
72
+ * Clear all stored states (useful for testing)
73
+ */
74
+ clear() {
75
+ this.internalStates.clear();
76
+ }
77
+ /**
78
+ * Get current state count (useful for testing/debugging)
79
+ */
80
+ get size() {
81
+ return this.internalStates.size;
82
+ }
83
+ /**
84
+ * Synchronous state access (for backward compatibility with CircuitBreaker.isOpen)
85
+ *
86
+ * Note: Only available on InMemoryCircuitBreakerStorage.
87
+ * Database-backed storage cannot provide sync access.
88
+ */
89
+ getStateSync(provider) {
90
+ return this.internalStates.get(provider) ?? null;
91
+ }
92
+ };
93
+ var defaultStorage = null;
94
+ function getInMemoryStorage() {
95
+ if (!defaultStorage) {
96
+ defaultStorage = new InMemoryCircuitBreakerStorage();
97
+ }
98
+ return defaultStorage;
99
+ }
100
+ function resetInMemoryStorage() {
101
+ if (defaultStorage) {
102
+ defaultStorage.clear();
103
+ }
104
+ defaultStorage = null;
105
+ }
106
+ async function migrateFromLegacyMap(legacyStates) {
107
+ const storage = new InMemoryCircuitBreakerStorage();
108
+ for (const [provider, state] of legacyStates) {
109
+ const record = {
110
+ provider: state.provider,
111
+ state: state.state,
112
+ failureCount: state.failureCount,
113
+ successCount: state.successCount,
114
+ lastFailure: state.lastFailure,
115
+ openedAt: state.openedAt,
116
+ nextRetryAt: state.nextRetryAt
117
+ };
118
+ await storage.setState(provider, record);
119
+ }
120
+ return storage;
121
+ }
122
+
123
+ // src/services/circuit-breaker.ts
124
+ var DEFAULT_CONFIG = {
125
+ failureThreshold: 5,
126
+ resetTimeoutMs: 6e4,
127
+ // 1 minute
128
+ halfOpenMaxRequests: 3
129
+ };
130
+ var CircuitBreaker = class {
131
+ config;
132
+ storage;
133
+ constructor(deps = {}) {
134
+ this.config = { ...DEFAULT_CONFIG, ...deps.config };
135
+ this.storage = deps.storage ?? new InMemoryCircuitBreakerStorage();
136
+ }
137
+ /**
138
+ * Check if a request can be executed for a provider
139
+ */
140
+ async canExecute(provider) {
141
+ const state = await this.getState(provider);
142
+ switch (state.state) {
143
+ case "closed":
144
+ return true;
145
+ case "open":
146
+ if (state.nextRetryAt && Date.now() >= state.nextRetryAt.getTime()) {
147
+ await this.transitionTo(provider, "half_open");
148
+ return true;
149
+ }
150
+ return false;
151
+ case "half_open":
152
+ return state.failureCount < this.config.halfOpenMaxRequests;
153
+ }
154
+ }
155
+ /**
156
+ * Record a successful request
157
+ */
158
+ async recordSuccess(provider) {
159
+ const state = await this.getState(provider);
160
+ if (state.state === "half_open") {
161
+ state.successCount++;
162
+ if (state.successCount >= this.config.halfOpenMaxRequests) {
163
+ await this.transitionTo(provider, "closed");
164
+ return;
165
+ }
166
+ } else if (state.state === "closed") {
167
+ state.failureCount = 0;
168
+ }
169
+ await this.storage.setState(provider, state);
170
+ }
171
+ /**
172
+ * Record a failed request
173
+ */
174
+ async recordFailure(provider) {
175
+ const state = await this.getState(provider);
176
+ state.failureCount++;
177
+ state.lastFailure = /* @__PURE__ */ new Date();
178
+ if (state.state === "half_open") {
179
+ await this.transitionTo(provider, "open");
180
+ } else if (state.state === "closed") {
181
+ if (state.failureCount >= this.config.failureThreshold) {
182
+ await this.transitionTo(provider, "open");
183
+ } else {
184
+ await this.storage.setState(provider, state);
185
+ }
186
+ } else {
187
+ await this.storage.setState(provider, state);
188
+ }
189
+ }
190
+ /**
191
+ * Get current state for a provider
192
+ */
193
+ async getState(provider) {
194
+ const stored = await this.storage.getState(provider);
195
+ return stored ?? createDefaultState(provider);
196
+ }
197
+ /**
198
+ * Check if circuit is open (provider unavailable)
199
+ */
200
+ isOpen(provider) {
201
+ return this.isOpenSync(provider);
202
+ }
203
+ /**
204
+ * Async version of isOpen
205
+ */
206
+ async isOpenAsync(provider) {
207
+ const state = await this.getState(provider);
208
+ return state.state === "open";
209
+ }
210
+ /**
211
+ * Manually reset a provider's circuit
212
+ */
213
+ async reset(provider) {
214
+ await this.storage.setState(provider, createDefaultState(provider));
215
+ }
216
+ /**
217
+ * Get all providers with open circuits
218
+ */
219
+ async getOpenCircuits() {
220
+ return this.storage.getOpenCircuits();
221
+ }
222
+ /**
223
+ * Get the storage instance (useful for testing)
224
+ */
225
+ getStorage() {
226
+ return this.storage;
227
+ }
228
+ /**
229
+ * Get configuration (useful for testing)
230
+ */
231
+ getConfig() {
232
+ return { ...this.config };
233
+ }
234
+ // ==========================================================================
235
+ // Private Methods
236
+ // ==========================================================================
237
+ async transitionTo(provider, newState) {
238
+ const state = await this.getState(provider);
239
+ const now = /* @__PURE__ */ new Date();
240
+ state.state = newState;
241
+ if (newState === "open") {
242
+ state.openedAt = now;
243
+ state.nextRetryAt = new Date(now.getTime() + this.config.resetTimeoutMs);
244
+ console.warn(
245
+ `[CIRCUIT_BREAKER] Circuit OPENED for ${provider}. Retry at: ${state.nextRetryAt.toISOString()}`
246
+ );
247
+ } else if (newState === "half_open") {
248
+ state.failureCount = 0;
249
+ state.successCount = 0;
250
+ console.info(`[CIRCUIT_BREAKER] Circuit HALF_OPEN for ${provider}`);
251
+ } else if (newState === "closed") {
252
+ state.failureCount = 0;
253
+ state.successCount = 0;
254
+ state.openedAt = null;
255
+ state.nextRetryAt = null;
256
+ console.info(`[CIRCUIT_BREAKER] Circuit CLOSED for ${provider}`);
257
+ }
258
+ await this.storage.setState(provider, state);
259
+ }
260
+ /**
261
+ * Synchronous check for backward compatibility
262
+ * Note: This always returns false for database-backed storage
263
+ */
264
+ isOpenSync(provider) {
265
+ if (this.storage instanceof InMemoryCircuitBreakerStorage) {
266
+ const state = this.storage.getStateSync(provider);
267
+ return state?.state === "open";
268
+ }
269
+ return false;
270
+ }
271
+ };
272
+ var circuitBreakerInstance = null;
273
+ var defaultStorage2 = null;
274
+ function getCircuitBreaker(config) {
275
+ if (!circuitBreakerInstance) {
276
+ if (!defaultStorage2) {
277
+ defaultStorage2 = new InMemoryCircuitBreakerStorage();
278
+ }
279
+ circuitBreakerInstance = new CircuitBreaker({
280
+ storage: defaultStorage2,
281
+ config
282
+ });
283
+ }
284
+ return circuitBreakerInstance;
285
+ }
286
+ function createCircuitBreaker(deps = {}) {
287
+ return new CircuitBreaker(deps);
288
+ }
289
+ function resetCircuitBreaker() {
290
+ circuitBreakerInstance = null;
291
+ if (defaultStorage2) {
292
+ defaultStorage2.clear();
293
+ }
294
+ defaultStorage2 = null;
295
+ }
296
+
297
+ // src/services/routing-engine.ts
298
+ function matchCardBinToRule(bin, rules) {
299
+ if (!bin || bin.length < 6) return null;
300
+ const binPrefix = bin.substring(0, 6);
301
+ for (const rule of rules) {
302
+ for (const range of rule.ranges) {
303
+ if (binPrefix >= range.start && binPrefix <= range.end) {
304
+ return { rule, issuer: range.issuer, country: range.country };
305
+ }
306
+ }
307
+ }
308
+ return null;
309
+ }
310
+ function getOptimalProviderFromPriorities(matchedBin, currency, requiresRecurring, availableProviders, priorities) {
311
+ const candidates = priorities.filter(
312
+ (p) => availableProviders.includes(p.provider)
313
+ );
314
+ if (candidates.length === 0) return availableProviders[0] ?? null;
315
+ const suitable = candidates.filter((p) => {
316
+ if (!p.supportsCurrency.includes(currency)) return false;
317
+ if (requiresRecurring && !p.supportsRecurring) return false;
318
+ return true;
319
+ });
320
+ if (suitable.length === 0) {
321
+ return candidates.sort((a, b) => a.priority - b.priority)[0]?.provider ?? null;
322
+ }
323
+ if (matchedBin) {
324
+ const localProviders = suitable.filter((p) => p.isLocalGateway);
325
+ if (localProviders.length > 0) {
326
+ return localProviders.sort((a, b) => a.priority - b.priority)[0].provider;
327
+ }
328
+ }
329
+ return suitable.sort((a, b) => a.priority - b.priority)[0].provider;
330
+ }
331
+ function getFallbackProvidersFromPriorities(primaryProvider, availableProviders, priorities) {
332
+ return priorities.filter(
333
+ (p) => p.provider !== primaryProvider && availableProviders.includes(p.provider)
334
+ ).sort((a, b) => a.priority - b.priority).map((p) => p.provider);
335
+ }
336
+ function getProviderFeeFromPriorities(provider, priorities) {
337
+ const config = priorities.find((p) => p.provider === provider);
338
+ return config?.maxFeePercent ?? 3;
339
+ }
340
+ var RoutingEngine = class {
341
+ config;
342
+ circuitBreaker;
343
+ routingRules;
344
+ constructor(deps = {}) {
345
+ this.config = deps.config ?? createPartialConfig({});
346
+ this.circuitBreaker = deps.circuitBreaker ?? getCircuitBreaker();
347
+ this.routingRules = deps.routingRules ?? {};
348
+ }
349
+ /**
350
+ * Determine optimal provider for a transaction
351
+ */
352
+ async route(context) {
353
+ const availability = getConfiguredProviders(this.config);
354
+ const availableProviders = this.getProviderList(availability);
355
+ if (availableProviders.length === 0) {
356
+ throw new Error("No payment providers configured");
357
+ }
358
+ if (context.savedPaymentMethodId && context.savedPaymentMethodProvider) {
359
+ return this.routeToSavedMethodProvider(context, availableProviders);
360
+ }
361
+ const binMatch = context.cardBin && this.routingRules.cardBinRules ? matchCardBinToRule(context.cardBin, this.routingRules.cardBinRules) : null;
362
+ const currencyRule = this.routingRules.currencyRules?.find(
363
+ (r) => r.currency === context.amount.currency
364
+ );
365
+ const healthyProviders = await this.getHealthyProviders(availableProviders);
366
+ const availableHealthy = availableProviders.filter((p) => healthyProviders.includes(p));
367
+ const effectiveProviders = availableHealthy.length > 0 ? availableHealthy : availableProviders;
368
+ if (binMatch && effectiveProviders.includes(binMatch.rule.preferredProvider)) {
369
+ const provider2 = binMatch.rule.preferredProvider;
370
+ const fallbacks2 = this.getFallbackProviders(provider2, availableProviders);
371
+ const feePercent = this.getProviderFee(provider2);
372
+ return {
373
+ provider: provider2,
374
+ reason: binMatch.issuer ? `Card (${binMatch.issuer}) matched BIN rule, routed to preferred provider` : "Card matched BIN rule, routed to preferred provider",
375
+ fallbackProviders: fallbacks2,
376
+ estimatedFeePercent: feePercent,
377
+ metadata: {
378
+ matchedBinRule: true,
379
+ cardIssuer: binMatch.issuer,
380
+ cardCountry: binMatch.country
381
+ }
382
+ };
383
+ }
384
+ if (currencyRule && effectiveProviders.includes(currencyRule.preferredProvider)) {
385
+ const provider2 = currencyRule.preferredProvider;
386
+ const fallbacks2 = this.getFallbackProviders(provider2, availableProviders);
387
+ const feePercent = this.getProviderFee(provider2);
388
+ return {
389
+ provider: provider2,
390
+ reason: `Currency ${context.amount.currency} routed to preferred provider`,
391
+ fallbackProviders: fallbacks2,
392
+ estimatedFeePercent: feePercent
393
+ };
394
+ }
395
+ const priorities = this.routingRules.providerPriorities;
396
+ if (priorities && priorities.length > 0) {
397
+ const provider2 = getOptimalProviderFromPriorities(
398
+ !!binMatch,
399
+ context.amount.currency,
400
+ context.isRecurring,
401
+ effectiveProviders,
402
+ priorities
403
+ );
404
+ if (provider2) {
405
+ const fallbacks2 = getFallbackProvidersFromPriorities(provider2, availableProviders, priorities);
406
+ const feePercent = getProviderFeeFromPriorities(provider2, priorities);
407
+ return {
408
+ provider: provider2,
409
+ reason: `Selected ${provider2} based on priority rules`,
410
+ fallbackProviders: fallbacks2,
411
+ estimatedFeePercent: feePercent,
412
+ metadata: {
413
+ matchedBinRule: !!binMatch,
414
+ cardIssuer: binMatch?.issuer,
415
+ cardCountry: binMatch?.country
416
+ }
417
+ };
418
+ }
419
+ }
420
+ const provider = effectiveProviders[0];
421
+ const fallbacks = effectiveProviders.slice(1);
422
+ return {
423
+ provider,
424
+ reason: `Default routing to ${provider}`,
425
+ fallbackProviders: fallbacks,
426
+ estimatedFeePercent: this.getProviderFee(provider)
427
+ };
428
+ }
429
+ /**
430
+ * Get next provider after a failure
431
+ */
432
+ async getFailoverProvider(failedProvider, _context) {
433
+ const availability = getConfiguredProviders(this.config);
434
+ const availableProviders = this.getProviderList(availability);
435
+ const healthyProviders = await this.getHealthyProviders(availableProviders);
436
+ const fallbacks = this.getFallbackProviders(failedProvider, availableProviders);
437
+ for (const provider of fallbacks) {
438
+ if (healthyProviders.includes(provider)) {
439
+ return provider;
440
+ }
441
+ }
442
+ return fallbacks[0] ?? null;
443
+ }
444
+ /**
445
+ * Check if a card BIN matches any configured rule
446
+ */
447
+ matchCardBin(bin) {
448
+ if (!this.routingRules.cardBinRules) return false;
449
+ return matchCardBinToRule(bin, this.routingRules.cardBinRules) !== null;
450
+ }
451
+ /**
452
+ * Get all available (healthy) providers
453
+ */
454
+ async getAvailableProviders() {
455
+ const availability = getConfiguredProviders(this.config);
456
+ const configured = this.getProviderList(availability);
457
+ return this.getHealthyProviders(configured);
458
+ }
459
+ /**
460
+ * Quick recommendation without full context
461
+ */
462
+ async getQuickRecommendation(currency, isRecurring) {
463
+ const availability = getConfiguredProviders(this.config);
464
+ const available = this.getProviderList(availability);
465
+ if (available.length === 0) return null;
466
+ const currencyRule = this.routingRules.currencyRules?.find(
467
+ (r) => r.currency === currency
468
+ );
469
+ if (currencyRule && available.includes(currencyRule.preferredProvider)) {
470
+ return currencyRule.preferredProvider;
471
+ }
472
+ const priorities = this.routingRules.providerPriorities;
473
+ if (priorities && priorities.length > 0) {
474
+ return getOptimalProviderFromPriorities(false, currency, isRecurring, available, priorities);
475
+ }
476
+ return available[0] ?? null;
477
+ }
478
+ /**
479
+ * Get current configuration (for testing/debugging)
480
+ */
481
+ getConfig() {
482
+ return this.config;
483
+ }
484
+ /**
485
+ * Get circuit breaker instance (for testing/debugging)
486
+ */
487
+ getCircuitBreaker() {
488
+ return this.circuitBreaker;
489
+ }
490
+ /**
491
+ * Get routing rules (for testing/debugging)
492
+ */
493
+ getRoutingRules() {
494
+ return this.routingRules;
495
+ }
496
+ // ==========================================================================
497
+ // Private Methods
498
+ // ==========================================================================
499
+ getProviderList(availability) {
500
+ const providers = [];
501
+ for (const [name, isAvailable] of Object.entries(availability)) {
502
+ if (isAvailable) providers.push(name);
503
+ }
504
+ return providers;
505
+ }
506
+ async getHealthyProviders(providers) {
507
+ const healthy = [];
508
+ for (const provider of providers) {
509
+ const isOpen = await this.circuitBreaker.isOpenAsync(provider);
510
+ if (!isOpen) {
511
+ healthy.push(provider);
512
+ }
513
+ }
514
+ return healthy;
515
+ }
516
+ routeToSavedMethodProvider(context, availableProviders) {
517
+ const provider = context.savedPaymentMethodProvider;
518
+ if (!availableProviders.includes(provider)) {
519
+ throw new Error(`Saved payment method provider '${provider}' is not available`);
520
+ }
521
+ return {
522
+ provider,
523
+ reason: "Using saved payment method provider",
524
+ fallbackProviders: [],
525
+ estimatedFeePercent: this.getProviderFee(provider)
526
+ };
527
+ }
528
+ getFallbackProviders(primaryProvider, availableProviders) {
529
+ const priorities = this.routingRules.providerPriorities;
530
+ if (priorities && priorities.length > 0) {
531
+ return getFallbackProvidersFromPriorities(primaryProvider, availableProviders, priorities);
532
+ }
533
+ return availableProviders.filter((p) => p !== primaryProvider);
534
+ }
535
+ getProviderFee(provider) {
536
+ const priorities = this.routingRules.providerPriorities;
537
+ if (priorities && priorities.length > 0) {
538
+ return getProviderFeeFromPriorities(provider, priorities);
539
+ }
540
+ return 3;
541
+ }
542
+ };
543
+ var routingEngineInstance = null;
544
+ function getRoutingEngine() {
545
+ if (!routingEngineInstance) {
546
+ routingEngineInstance = new RoutingEngine();
547
+ }
548
+ return routingEngineInstance;
549
+ }
550
+ function createRoutingEngine(deps = {}) {
551
+ return new RoutingEngine(deps);
552
+ }
553
+ function resetRoutingEngine() {
554
+ routingEngineInstance = null;
555
+ }
556
+
557
+ // src/services/payment-orchestrator.ts
558
+ var PaymentOrchestrator = class {
559
+ providers;
560
+ routingEngine;
561
+ circuitBreaker;
562
+ constructor(deps) {
563
+ this.providers = deps.providers;
564
+ this.routingEngine = deps.routingEngine ?? getRoutingEngine();
565
+ this.circuitBreaker = deps.circuitBreaker ?? getCircuitBreaker();
566
+ }
567
+ /**
568
+ * Initiate a new payment
569
+ */
570
+ async initiatePayment(params) {
571
+ const internalPaymentId = `pay_${randomUUID()}`;
572
+ const idempotencyKey = `idem_${randomUUID()}`;
573
+ try {
574
+ const routing = await this.routingEngine.route({
575
+ userId: params.userId,
576
+ amount: params.amount,
577
+ cardBin: params.cardBin,
578
+ preferredProvider: params.preferredProvider,
579
+ isRecurring: params.transactionType !== "one_time_purchase"
580
+ });
581
+ const provider = this.getProvider(routing.provider);
582
+ if (!provider) {
583
+ return this.tryFailover(params, routing, internalPaymentId);
584
+ }
585
+ if (!await this.circuitBreaker.canExecute(routing.provider)) {
586
+ return this.tryFailover(params, routing, internalPaymentId);
587
+ }
588
+ const result = await provider.createPaymentIntent({
589
+ amount: params.amount,
590
+ userId: params.userId,
591
+ idempotencyKey,
592
+ description: params.description,
593
+ metadata: params.metadata,
594
+ returnUrl: params.returnUrl,
595
+ captureMethod: params.autoCapture ? "automatic" : "manual"
596
+ });
597
+ if (!result.success) {
598
+ await this.circuitBreaker.recordFailure(routing.provider);
599
+ return this.tryFailover(params, routing, internalPaymentId);
600
+ }
601
+ await this.circuitBreaker.recordSuccess(routing.provider);
602
+ return {
603
+ success: true,
604
+ transactionId: result.providerIntentId,
605
+ internalPaymentId,
606
+ provider: routing.provider,
607
+ clientSecret: result.clientSecret,
608
+ redirectUrl: result.redirectUrl
609
+ };
610
+ } catch (error) {
611
+ return {
612
+ success: false,
613
+ transactionId: "",
614
+ internalPaymentId,
615
+ provider: "unknown",
616
+ error: error instanceof Error ? error.message : "Unknown error"
617
+ };
618
+ }
619
+ }
620
+ /**
621
+ * Confirm a payment after user authorization
622
+ */
623
+ async confirmPayment(params) {
624
+ const provider = this.getProvider(params.provider);
625
+ if (!provider) {
626
+ return {
627
+ success: false,
628
+ transactionId: params.transactionId,
629
+ status: "failed",
630
+ error: `Provider ${params.provider} not available`
631
+ };
632
+ }
633
+ const result = await provider.authorize({
634
+ providerIntentId: params.providerIntentId,
635
+ idempotencyKey: `auth_${params.internalPaymentId}`
636
+ });
637
+ if (!result.success) {
638
+ return {
639
+ success: false,
640
+ transactionId: params.transactionId,
641
+ status: "failed",
642
+ error: result.error
643
+ };
644
+ }
645
+ return {
646
+ success: true,
647
+ transactionId: params.transactionId,
648
+ status: result.status ?? "authorized"
649
+ };
650
+ }
651
+ /**
652
+ * Capture an authorized payment (J5 completion)
653
+ */
654
+ async capturePayment(params) {
655
+ const provider = this.getProvider(params.provider);
656
+ if (!provider) {
657
+ return {
658
+ success: false,
659
+ status: "failed",
660
+ error: `Provider ${params.provider} not available`
661
+ };
662
+ }
663
+ const result = await provider.capture({
664
+ providerIntentId: params.providerIntentId,
665
+ authorizationCode: params.providerIntentId,
666
+ amount: params.amount,
667
+ idempotencyKey: `cap_${params.transactionId}`
668
+ });
669
+ if (!result.success) {
670
+ return {
671
+ success: false,
672
+ status: "failed",
673
+ error: result.error
674
+ };
675
+ }
676
+ return {
677
+ success: true,
678
+ status: "captured",
679
+ capturedAmount: result.capturedAmount
680
+ };
681
+ }
682
+ /**
683
+ * Get the routing engine (for testing/debugging)
684
+ */
685
+ getRoutingEngine() {
686
+ return this.routingEngine;
687
+ }
688
+ /**
689
+ * Get the circuit breaker (for testing/debugging)
690
+ */
691
+ getCircuitBreaker() {
692
+ return this.circuitBreaker;
693
+ }
694
+ /**
695
+ * Get available providers (for testing/debugging)
696
+ */
697
+ getProviders() {
698
+ return new Map(this.providers);
699
+ }
700
+ // ==========================================================================
701
+ // Private Methods
702
+ // ==========================================================================
703
+ getProvider(name) {
704
+ return this.providers.get(name);
705
+ }
706
+ async tryFailover(params, routing, internalPaymentId) {
707
+ for (const fallback of routing.fallbackProviders) {
708
+ const provider = this.getProvider(fallback);
709
+ if (!provider) continue;
710
+ if (!await this.circuitBreaker.canExecute(fallback)) continue;
711
+ const result = await provider.createPaymentIntent({
712
+ amount: params.amount,
713
+ userId: params.userId,
714
+ idempotencyKey: `idem_${randomUUID()}`,
715
+ description: params.description,
716
+ metadata: params.metadata,
717
+ returnUrl: params.returnUrl,
718
+ captureMethod: params.autoCapture ? "automatic" : "manual"
719
+ });
720
+ if (result.success) {
721
+ await this.circuitBreaker.recordSuccess(fallback);
722
+ return {
723
+ success: true,
724
+ transactionId: result.providerIntentId,
725
+ internalPaymentId,
726
+ provider: fallback,
727
+ clientSecret: result.clientSecret
728
+ };
729
+ }
730
+ await this.circuitBreaker.recordFailure(fallback);
731
+ }
732
+ return {
733
+ success: false,
734
+ transactionId: "",
735
+ internalPaymentId,
736
+ provider: routing.provider,
737
+ error: "All payment providers failed"
738
+ };
739
+ }
740
+ };
741
+ function createPaymentOrchestrator(deps) {
742
+ return new PaymentOrchestrator(deps);
743
+ }
744
+ export {
745
+ CircuitBreaker,
746
+ InMemoryCircuitBreakerStorage,
747
+ PaymentOrchestrator,
748
+ RoutingEngine,
749
+ createCircuitBreaker,
750
+ createDefaultState,
751
+ createPaymentOrchestrator,
752
+ createRoutingEngine,
753
+ getCircuitBreaker,
754
+ getInMemoryStorage,
755
+ getRoutingEngine,
756
+ isCircuitOpen,
757
+ migrateFromLegacyMap,
758
+ resetCircuitBreaker,
759
+ resetInMemoryStorage,
760
+ resetRoutingEngine,
761
+ shouldAttemptHalfOpen
762
+ };
763
+ //# sourceMappingURL=index.js.map