@digilogiclabs/saas-factory-payments 1.2.3 → 1.2.5

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.d.mts CHANGED
@@ -1,132 +1,5 @@
1
- import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-x4PgwjGU.mjs';
2
- export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-x4PgwjGU.mjs';
3
- import React from 'react';
4
- export { a as PricingTable, P as StripePaymentForm, b as StripePaymentFormProps, S as SubscriptionManager, c as SubscriptionManagerProps } from './SubscriptionManager-DCk9BiEL.mjs';
5
- import '@stripe/stripe-js';
6
-
7
- interface CheckoutParams {
8
- priceId: string;
9
- mode?: 'payment' | 'subscription';
10
- customerId?: string;
11
- customerEmail?: string;
12
- allowPromotionCodes?: boolean;
13
- successUrl?: string;
14
- cancelUrl?: string;
15
- metadata?: Record<string, string | number | null>;
16
- amount?: number;
17
- currency?: string;
18
- description?: string;
19
- }
20
- interface CheckoutSession {
21
- id: string;
22
- url?: string | null;
23
- clientSecret?: string;
24
- status: 'open' | 'complete' | 'expired';
25
- amountTotal?: number;
26
- currency?: string;
27
- customerEmail?: string;
28
- subscriptionId?: string;
29
- customer_id?: string;
30
- amount_total?: number;
31
- mode?: 'payment' | 'subscription';
32
- payment_status?: 'paid' | 'unpaid';
33
- expires_at?: Date;
34
- metadata?: Record<string, any>;
35
- }
36
-
37
- declare enum PaymentErrorType {
38
- CARD_DECLINED = "CARD_DECLINED",
39
- INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
40
- CUSTOMER_NOT_FOUND = "CUSTOMER_NOT_FOUND",
41
- SUBSCRIPTION_NOT_FOUND = "SUBSCRIPTION_NOT_FOUND",
42
- NETWORK_ERROR = "NETWORK_ERROR",
43
- CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
44
- WEBHOOK_ERROR = "WEBHOOK_ERROR",
45
- VALIDATION_ERROR = "VALIDATION_ERROR",
46
- PROVIDER_NOT_CONFIGURED = "PROVIDER_NOT_CONFIGURED",
47
- UNKNOWN_ERROR = "UNKNOWN_ERROR",
48
- INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
49
- AUTHENTICATION_ERROR = "AUTHENTICATION_ERROR",
50
- NOT_FOUND = "NOT_FOUND",
51
- INVALID_REQUEST = "INVALID_REQUEST",
52
- API_ERROR = "API_ERROR",
53
- PERMISSION_DENIED = "PERMISSION_DENIED",
54
- WEBHOOK_VERIFICATION_FAILED = "WEBHOOK_VERIFICATION_FAILED"
55
- }
56
- interface PaymentError extends Error {
57
- type: PaymentErrorType;
58
- code?: string;
59
- details?: Record<string, unknown>;
60
- }
61
- declare class PaymentsError extends Error implements PaymentError {
62
- type: PaymentErrorType;
63
- code?: string;
64
- details?: Record<string, unknown>;
65
- constructor(type: PaymentErrorType, message: string, code?: string, details?: Record<string, unknown>);
66
- }
67
-
68
- type PaymentEvent = {
69
- type: 'checkoutSuccess';
70
- session: CheckoutSession;
71
- } | {
72
- type: 'paymentMethodAdded';
73
- customer: Customer;
74
- } | {
75
- type: 'subscriptionCreated';
76
- subscription: Subscription;
77
- } | {
78
- type: 'subscriptionUpdated';
79
- subscription: Subscription;
80
- } | {
81
- type: 'subscriptionCanceled';
82
- subscription: Subscription;
83
- } | {
84
- type: 'error';
85
- error: PaymentError;
86
- };
87
-
88
- interface PaymentProvider {
89
- name: string;
90
- initialize(): Promise<void>;
91
- createCheckoutSession(params: CheckoutParams): Promise<CheckoutSession>;
92
- retrieveCheckoutSession(sessionId: string): Promise<CheckoutSession>;
93
- createCustomer(params: CustomerCreateParams): Promise<Customer>;
94
- retrieveCustomer(customerId: string): Promise<Customer | null>;
95
- createSubscription(params: SubscriptionCreateParams): Promise<Subscription>;
96
- cancelSubscription(subscriptionId: string): Promise<void>;
97
- reactivateSubscription(subscriptionId: string): Promise<void>;
98
- listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
99
- retrieveSubscription(subscriptionId: string): Promise<Subscription | null>;
100
- updateSubscription(subscriptionId: string, params: SubscriptionUpdateParams): Promise<Subscription>;
101
- }
102
- interface PaymentsProviderState {
103
- customer: Customer | null;
104
- subscriptions: Subscription[];
105
- activeSubscription: Subscription | null;
106
- loading: boolean;
107
- error: PaymentError | null;
108
- initialized: boolean;
109
- config: PaymentsConfig | null;
110
- isLoading: boolean;
111
- isError: boolean;
112
- }
113
- interface PaymentsProviderActions {
114
- initialize: (config?: PaymentsConfig) => Promise<void>;
115
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
116
- retrieveCustomer: (customerId: string) => Promise<Customer | null>;
117
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
118
- retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
119
- createSubscription: (params: SubscriptionCreateParams) => Promise<Subscription>;
120
- cancelSubscription: (subscriptionId: string) => Promise<void>;
121
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
122
- listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
123
- retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
124
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
125
- refreshCustomer: (customerId: string) => Promise<void>;
126
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
127
- reset: () => void;
128
- }
129
- type PaymentsStore = PaymentsProviderState & PaymentsProviderActions;
1
+ import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as PaymentProvider, c as PaymentProviderType, C as CheckoutParams, d as CheckoutSession, e as CustomerCreateParams, f as Customer, g as SubscriptionCreateParams, h as Subscription, i as SubscriptionUpdateParams, j as PaymentErrorType, k as PaymentsError, l as PaymentMethod } from './provider-CH-Pf2B0.mjs';
2
+ export { p as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, z as CheckoutSessionParams, x as CustomerUpdateParams, q as INACTIVE_STATUSES, s as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, o as IncompleteSubscriptionStatus, F as Invoice, r as PROBLEMATIC_STATUSES, G as PaymentError, H as PaymentEvent, D as PaymentIntentParams, K as PaymentsProviderActions, J as PaymentsProviderState, L as PaymentsStore, n as ProblematicSubscriptionStatus, y as StripeConfig, E as StripeError, m as SubscriptionItem, W as WebhookEvent, t as isActiveSubscription, u as isInactiveSubscription, w as isIncompleteSubscription, v as isProblematicSubscription } from './provider-CH-Pf2B0.mjs';
130
3
 
131
4
  declare const STRIPE_API_VERSION = "2023-10-16";
132
5
  declare const PAYMENT_METHODS: {
@@ -366,61 +239,4 @@ declare class MockPaymentProvider extends BasePaymentProvider implements Payment
366
239
  listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
367
240
  }
368
241
 
369
- interface PaymentsContextType {
370
- config: PaymentsConfig | null;
371
- initialized: boolean;
372
- loading: boolean;
373
- error: PaymentError | null;
374
- customer: Customer | null;
375
- subscriptions: Subscription[];
376
- activeSubscription: Subscription | null;
377
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
378
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
379
- cancelSubscription: (subscriptionId: string) => Promise<void>;
380
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
381
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
382
- refreshCustomer: (customerId: string) => Promise<void>;
383
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
384
- reset: () => void;
385
- }
386
- interface PaymentsProviderProps {
387
- children: React.ReactNode;
388
- config?: PaymentsConfig;
389
- onPaymentSuccess?: (event: PaymentEvent) => void;
390
- onPaymentError?: (error: PaymentError) => void;
391
- }
392
- declare const PaymentsProvider: React.FC<PaymentsProviderProps>;
393
- declare const usePaymentsContext: () => PaymentsContextType;
394
-
395
- interface UsePaymentsStore {
396
- config: PaymentsConfig | null;
397
- provider: PaymentProvider | null;
398
- initialized: boolean;
399
- loading: boolean;
400
- error: PaymentsError | null;
401
- isLoading: boolean;
402
- isError: boolean;
403
- customer: Customer | null;
404
- subscriptions: Subscription[];
405
- activeSubscription: Subscription | null;
406
- initialize: (config?: PaymentsConfig) => Promise<void>;
407
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
408
- retrieveCustomer: (customerId: string) => Promise<Customer | null>;
409
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
410
- retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
411
- createSubscription: (params: {
412
- priceId: string;
413
- quantity?: number;
414
- }) => Promise<Subscription>;
415
- cancelSubscription: (subscriptionId: string) => Promise<void>;
416
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
417
- listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
418
- retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
419
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
420
- refreshCustomer: (customerId: string) => Promise<void>;
421
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
422
- reset: () => void;
423
- }
424
- declare const usePayments: () => UsePaymentsStore;
425
-
426
- export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
242
+ export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, CheckoutParams, CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, PaymentErrorType, PaymentMethod, PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
package/dist/index.d.ts CHANGED
@@ -1,132 +1,5 @@
1
- import { C as Customer, S as Subscription, a as CustomerCreateParams, b as SubscriptionCreateParams, c as SubscriptionStatus, d as SubscriptionUpdateParams, P as PaymentsConfig, e as PricingPlan, f as PaymentProviderType, g as PaymentMethod } from './config-x4PgwjGU.js';
2
- export { k as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, u as CheckoutSessionParams, s as CustomerUpdateParams, l as INACTIVE_STATUSES, n as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, j as IncompleteSubscriptionStatus, x as Invoice, m as PROBLEMATIC_STATUSES, v as PaymentIntentParams, i as ProblematicSubscriptionStatus, t as StripeConfig, w as StripeError, h as SubscriptionItem, W as WebhookEvent, o as isActiveSubscription, p as isInactiveSubscription, r as isIncompleteSubscription, q as isProblematicSubscription } from './config-x4PgwjGU.js';
3
- import React from 'react';
4
- export { a as PricingTable, P as StripePaymentForm, b as StripePaymentFormProps, S as SubscriptionManager, c as SubscriptionManagerProps } from './SubscriptionManager-Cnw5n74K.js';
5
- import '@stripe/stripe-js';
6
-
7
- interface CheckoutParams {
8
- priceId: string;
9
- mode?: 'payment' | 'subscription';
10
- customerId?: string;
11
- customerEmail?: string;
12
- allowPromotionCodes?: boolean;
13
- successUrl?: string;
14
- cancelUrl?: string;
15
- metadata?: Record<string, string | number | null>;
16
- amount?: number;
17
- currency?: string;
18
- description?: string;
19
- }
20
- interface CheckoutSession {
21
- id: string;
22
- url?: string | null;
23
- clientSecret?: string;
24
- status: 'open' | 'complete' | 'expired';
25
- amountTotal?: number;
26
- currency?: string;
27
- customerEmail?: string;
28
- subscriptionId?: string;
29
- customer_id?: string;
30
- amount_total?: number;
31
- mode?: 'payment' | 'subscription';
32
- payment_status?: 'paid' | 'unpaid';
33
- expires_at?: Date;
34
- metadata?: Record<string, any>;
35
- }
36
-
37
- declare enum PaymentErrorType {
38
- CARD_DECLINED = "CARD_DECLINED",
39
- INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
40
- CUSTOMER_NOT_FOUND = "CUSTOMER_NOT_FOUND",
41
- SUBSCRIPTION_NOT_FOUND = "SUBSCRIPTION_NOT_FOUND",
42
- NETWORK_ERROR = "NETWORK_ERROR",
43
- CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
44
- WEBHOOK_ERROR = "WEBHOOK_ERROR",
45
- VALIDATION_ERROR = "VALIDATION_ERROR",
46
- PROVIDER_NOT_CONFIGURED = "PROVIDER_NOT_CONFIGURED",
47
- UNKNOWN_ERROR = "UNKNOWN_ERROR",
48
- INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
49
- AUTHENTICATION_ERROR = "AUTHENTICATION_ERROR",
50
- NOT_FOUND = "NOT_FOUND",
51
- INVALID_REQUEST = "INVALID_REQUEST",
52
- API_ERROR = "API_ERROR",
53
- PERMISSION_DENIED = "PERMISSION_DENIED",
54
- WEBHOOK_VERIFICATION_FAILED = "WEBHOOK_VERIFICATION_FAILED"
55
- }
56
- interface PaymentError extends Error {
57
- type: PaymentErrorType;
58
- code?: string;
59
- details?: Record<string, unknown>;
60
- }
61
- declare class PaymentsError extends Error implements PaymentError {
62
- type: PaymentErrorType;
63
- code?: string;
64
- details?: Record<string, unknown>;
65
- constructor(type: PaymentErrorType, message: string, code?: string, details?: Record<string, unknown>);
66
- }
67
-
68
- type PaymentEvent = {
69
- type: 'checkoutSuccess';
70
- session: CheckoutSession;
71
- } | {
72
- type: 'paymentMethodAdded';
73
- customer: Customer;
74
- } | {
75
- type: 'subscriptionCreated';
76
- subscription: Subscription;
77
- } | {
78
- type: 'subscriptionUpdated';
79
- subscription: Subscription;
80
- } | {
81
- type: 'subscriptionCanceled';
82
- subscription: Subscription;
83
- } | {
84
- type: 'error';
85
- error: PaymentError;
86
- };
87
-
88
- interface PaymentProvider {
89
- name: string;
90
- initialize(): Promise<void>;
91
- createCheckoutSession(params: CheckoutParams): Promise<CheckoutSession>;
92
- retrieveCheckoutSession(sessionId: string): Promise<CheckoutSession>;
93
- createCustomer(params: CustomerCreateParams): Promise<Customer>;
94
- retrieveCustomer(customerId: string): Promise<Customer | null>;
95
- createSubscription(params: SubscriptionCreateParams): Promise<Subscription>;
96
- cancelSubscription(subscriptionId: string): Promise<void>;
97
- reactivateSubscription(subscriptionId: string): Promise<void>;
98
- listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
99
- retrieveSubscription(subscriptionId: string): Promise<Subscription | null>;
100
- updateSubscription(subscriptionId: string, params: SubscriptionUpdateParams): Promise<Subscription>;
101
- }
102
- interface PaymentsProviderState {
103
- customer: Customer | null;
104
- subscriptions: Subscription[];
105
- activeSubscription: Subscription | null;
106
- loading: boolean;
107
- error: PaymentError | null;
108
- initialized: boolean;
109
- config: PaymentsConfig | null;
110
- isLoading: boolean;
111
- isError: boolean;
112
- }
113
- interface PaymentsProviderActions {
114
- initialize: (config?: PaymentsConfig) => Promise<void>;
115
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
116
- retrieveCustomer: (customerId: string) => Promise<Customer | null>;
117
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
118
- retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
119
- createSubscription: (params: SubscriptionCreateParams) => Promise<Subscription>;
120
- cancelSubscription: (subscriptionId: string) => Promise<void>;
121
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
122
- listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
123
- retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
124
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
125
- refreshCustomer: (customerId: string) => Promise<void>;
126
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
127
- reset: () => void;
128
- }
129
- type PaymentsStore = PaymentsProviderState & PaymentsProviderActions;
1
+ import { P as PricingPlan, a as PaymentsConfig, S as SubscriptionStatus, b as PaymentProvider, c as PaymentProviderType, C as CheckoutParams, d as CheckoutSession, e as CustomerCreateParams, f as Customer, g as SubscriptionCreateParams, h as Subscription, i as SubscriptionUpdateParams, j as PaymentErrorType, k as PaymentsError, l as PaymentMethod } from './provider-CH-Pf2B0.js';
2
+ export { p as ACTIVE_STATUSES, A as ActiveSubscriptionStatus, B as BillingAddress, z as CheckoutSessionParams, x as CustomerUpdateParams, q as INACTIVE_STATUSES, s as INCOMPLETE_STATUSES, I as InactiveSubscriptionStatus, o as IncompleteSubscriptionStatus, F as Invoice, r as PROBLEMATIC_STATUSES, G as PaymentError, H as PaymentEvent, D as PaymentIntentParams, K as PaymentsProviderActions, J as PaymentsProviderState, L as PaymentsStore, n as ProblematicSubscriptionStatus, y as StripeConfig, E as StripeError, m as SubscriptionItem, W as WebhookEvent, t as isActiveSubscription, u as isInactiveSubscription, w as isIncompleteSubscription, v as isProblematicSubscription } from './provider-CH-Pf2B0.js';
130
3
 
131
4
  declare const STRIPE_API_VERSION = "2023-10-16";
132
5
  declare const PAYMENT_METHODS: {
@@ -366,61 +239,4 @@ declare class MockPaymentProvider extends BasePaymentProvider implements Payment
366
239
  listSubscriptions(customerId: string, status?: SubscriptionStatus): Promise<Subscription[]>;
367
240
  }
368
241
 
369
- interface PaymentsContextType {
370
- config: PaymentsConfig | null;
371
- initialized: boolean;
372
- loading: boolean;
373
- error: PaymentError | null;
374
- customer: Customer | null;
375
- subscriptions: Subscription[];
376
- activeSubscription: Subscription | null;
377
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
378
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
379
- cancelSubscription: (subscriptionId: string) => Promise<void>;
380
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
381
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
382
- refreshCustomer: (customerId: string) => Promise<void>;
383
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
384
- reset: () => void;
385
- }
386
- interface PaymentsProviderProps {
387
- children: React.ReactNode;
388
- config?: PaymentsConfig;
389
- onPaymentSuccess?: (event: PaymentEvent) => void;
390
- onPaymentError?: (error: PaymentError) => void;
391
- }
392
- declare const PaymentsProvider: React.FC<PaymentsProviderProps>;
393
- declare const usePaymentsContext: () => PaymentsContextType;
394
-
395
- interface UsePaymentsStore {
396
- config: PaymentsConfig | null;
397
- provider: PaymentProvider | null;
398
- initialized: boolean;
399
- loading: boolean;
400
- error: PaymentsError | null;
401
- isLoading: boolean;
402
- isError: boolean;
403
- customer: Customer | null;
404
- subscriptions: Subscription[];
405
- activeSubscription: Subscription | null;
406
- initialize: (config?: PaymentsConfig) => Promise<void>;
407
- createCustomer: (params: CustomerCreateParams) => Promise<Customer>;
408
- retrieveCustomer: (customerId: string) => Promise<Customer | null>;
409
- createCheckoutSession: (params: CheckoutParams) => Promise<CheckoutSession>;
410
- retrieveCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
411
- createSubscription: (params: {
412
- priceId: string;
413
- quantity?: number;
414
- }) => Promise<Subscription>;
415
- cancelSubscription: (subscriptionId: string) => Promise<void>;
416
- reactivateSubscription: (subscriptionId: string) => Promise<void>;
417
- listSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<Subscription[]>;
418
- retrieveSubscription: (subscriptionId: string) => Promise<Subscription | null>;
419
- updateSubscription: (subscriptionId: string, params: SubscriptionUpdateParams) => Promise<Subscription>;
420
- refreshCustomer: (customerId: string) => Promise<void>;
421
- refreshSubscriptions: (customerId: string, status?: SubscriptionStatus) => Promise<void>;
422
- reset: () => void;
423
- }
424
- declare const usePayments: () => UsePaymentsStore;
425
-
426
- export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, type CheckoutParams, type CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, type PaymentError, PaymentErrorType, type PaymentEvent, PaymentMethod, type PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PaymentsProvider, type PaymentsProviderActions, type PaymentsProviderState, type PaymentsStore, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, usePayments, usePaymentsContext, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
242
+ export { BILLING_INTERVALS, CHECKOUT_MODE, CURRENCY_SYMBOLS, CheckoutParams, CheckoutSession, Customer, CustomerCreateParams, DEFAULT_CURRENCY, ERROR_MESSAGES, type EnvironmentConfig, INVOICE_STATUS, MockPaymentProvider, PAYMENT_METHODS, PaymentErrorType, PaymentMethod, PaymentProvider, PaymentProviderFactory, PaymentProviderType, PaymentsConfig, PaymentsError, PricingPlan, STRIPE_API_VERSION, SUBSCRIPTION_STATUS, StripePaymentProvider, Subscription, SubscriptionCreateParams, SubscriptionStatus, SubscriptionUpdateParams, WEBHOOK_EVENTS, calculateTax, formatAmountWithTax, formatBillingInterval, formatCardBrand, formatCurrency, formatDate, formatPaymentMethodDisplay, formatPricingPlan, formatRelativeTime, formatSubscriptionStatus, formatTaxRate, formatTrialPeriod, getEnvironmentConfig, isClient, isDevelopment, isProduction, isServer, truncateText, validateAmount, validateCard, validateCurrentEnvironment, validateEmail, validateEnvironment, validatePaymentsConfig, validatePhoneNumber, validatePricingPlan, validateStripeId };
package/dist/index.js CHANGED
@@ -1,17 +1,2 @@
1
- "use strict";var Me=Object.create;var q=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Ke=(r,e)=>{for(var t in e)q(r,t,{get:e[t],enumerable:!0})},se=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Le(e))!Be.call(r,n)&&n!==t&&q(r,n,{get:()=>e[n],enumerable:!(i=Fe(e,n))||i.enumerable});return r};var $e=(r,e,t)=>(t=r!=null?Me(Ve(r)):{},se(e||!r||!r.__esModule?q(t,"default",{value:r,enumerable:!0}):t,r)),Ye=r=>se(q({},"__esModule",{value:!0}),r);var ft={};Ke(ft,{ACTIVE_STATUSES:()=>ce,BILLING_INTERVALS:()=>Qe,CHECKOUT_MODE:()=>Ze,CURRENCY_SYMBOLS:()=>ee,DEFAULT_CURRENCY:()=>H,ERROR_MESSAGES:()=>y,INACTIVE_STATUSES:()=>ue,INCOMPLETE_STATUSES:()=>me,INVOICE_STATUS:()=>Je,MockPaymentProvider:()=>G,PAYMENT_METHODS:()=>Xe,PROBLEMATIC_STATUSES:()=>le,PaymentErrorType:()=>M,PaymentProviderFactory:()=>R,PaymentsError:()=>c,PaymentsProvider:()=>Ne,PricingTable:()=>ne,STRIPE_API_VERSION:()=>He,SUBSCRIPTION_STATUS:()=>je,StripePaymentForm:()=>Z,StripePaymentProvider:()=>Y,SubscriptionManager:()=>oe,SubscriptionStatus:()=>ae,WEBHOOK_EVENTS:()=>et,calculateTax:()=>ie,formatAmountWithTax:()=>Ee,formatBillingInterval:()=>ot,formatCardBrand:()=>Se,formatCurrency:()=>V,formatDate:()=>be,formatPaymentMethodDisplay:()=>at,formatPricingPlan:()=>te,formatRelativeTime:()=>nt,formatSubscriptionStatus:()=>it,formatTaxRate:()=>ye,formatTrialPeriod:()=>re,getEnvironmentConfig:()=>ge,isActiveSubscription:()=>Ge,isClient:()=>dt,isDevelopment:()=>ut,isInactiveSubscription:()=>We,isIncompleteSubscription:()=>qe,isProblematicSubscription:()=>ze,isProduction:()=>lt,isServer:()=>mt,truncateText:()=>st,usePayments:()=>Te,usePaymentsContext:()=>$,validateAmount:()=>fe,validateCard:()=>Pe,validateCurrentEnvironment:()=>ct,validateEmail:()=>X,validateEnvironment:()=>he,validatePaymentsConfig:()=>de,validatePhoneNumber:()=>tt,validatePricingPlan:()=>pe,validateStripeId:()=>j});module.exports=Ye(ft);var ae=(l=>(l.ACTIVE="active",l.CANCELED="canceled",l.PAST_DUE="past_due",l.UNPAID="unpaid",l.INCOMPLETE="incomplete",l.INCOMPLETE_EXPIRED="incomplete_expired",l.TRIALING="trialing",l.ENDED="ended",l.ALL="all",l))(ae||{}),ce=["active","trialing"],ue=["canceled","ended"],le=["past_due","unpaid"],me=["incomplete","incomplete_expired"],Ge=r=>ce.includes(r),We=r=>ue.includes(r),ze=r=>le.includes(r),qe=r=>me.includes(r);var M=(h=>(h.CARD_DECLINED="CARD_DECLINED",h.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",h.CUSTOMER_NOT_FOUND="CUSTOMER_NOT_FOUND",h.SUBSCRIPTION_NOT_FOUND="SUBSCRIPTION_NOT_FOUND",h.NETWORK_ERROR="NETWORK_ERROR",h.CONFIGURATION_ERROR="CONFIGURATION_ERROR",h.WEBHOOK_ERROR="WEBHOOK_ERROR",h.VALIDATION_ERROR="VALIDATION_ERROR",h.PROVIDER_NOT_CONFIGURED="PROVIDER_NOT_CONFIGURED",h.UNKNOWN_ERROR="UNKNOWN_ERROR",h.INITIALIZATION_ERROR="INITIALIZATION_ERROR",h.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",h.NOT_FOUND="NOT_FOUND",h.INVALID_REQUEST="INVALID_REQUEST",h.API_ERROR="API_ERROR",h.PERMISSION_DENIED="PERMISSION_DENIED",h.WEBHOOK_VERIFICATION_FAILED="WEBHOOK_VERIFICATION_FAILED",h))(M||{}),c=class r extends Error{type;code;details;constructor(e,t,i,n){super(t),this.name="PaymentsError",this.type=e,this.code=i,this.details=n,Object.setPrototypeOf(this,r.prototype)}};var He="2023-10-16",Xe={CARD:"card",BANK_ACCOUNT:"bank_account",SEPA_DEBIT:"sepa_debit",IDEAL:"ideal",SOFORT:"sofort"},je={ACTIVE:"active",CANCELED:"canceled",PAST_DUE:"past_due",UNPAID:"unpaid",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",TRIALING:"trialing"},Je={DRAFT:"draft",OPEN:"open",PAID:"paid",UNCOLLECTIBLE:"uncollectible",VOID:"void"},Ze={PAYMENT:"payment",SUBSCRIPTION:"subscription",SETUP:"setup"},Qe={DAY:"day",WEEK:"week",MONTH:"month",YEAR:"year"},ee={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},H="USD",et={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"},y={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var X=r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),tt=r=>/^\+?[\d\s-()]{10,}$/.test(r),de=r=>{let e=[];return r.publishableKey||e.push("publishableKey is required"),r.provider||e.push("provider is required"),r.provider!=="stripe"&&e.push("Only stripe provider is currently supported"),r.environment||e.push("environment is required"),r.environment&&!["development","production"].includes(r.environment)&&e.push('environment must be either "development" or "production"'),r.publishableKey&&!r.publishableKey.startsWith("pk_")&&e.push('publishableKey must start with "pk_"'),r.secretKey&&!r.secretKey.startsWith("sk_")&&e.push('secretKey must start with "sk_"'),r.webhookSecret&&!r.webhookSecret.startsWith("whsec_")&&e.push('webhookSecret must start with "whsec_"'),{isValid:e.length===0,errors:e}},pe=r=>{let e=[];return r.id||e.push("id is required"),r.name||e.push("name is required"),(typeof r.price!="number"||r.price<0)&&e.push("price must be a non-negative number"),r.currency||e.push("currency is required"),r.interval||e.push("interval is required"),["day","week","month","year"].includes(r.interval)||e.push("interval must be one of: day, week, month, year"),r.stripePriceId||e.push("stripePriceId is required"),r.stripePriceId&&!r.stripePriceId.startsWith("price_")&&e.push('stripePriceId must start with "price_"'),Array.isArray(r.features)||e.push("features must be an array"),r.intervalCount&&(typeof r.intervalCount!="number"||r.intervalCount<1)&&e.push("intervalCount must be a positive number"),r.trialPeriodDays&&(typeof r.trialPeriodDays!="number"||r.trialPeriodDays<0)&&e.push("trialPeriodDays must be a non-negative number"),{isValid:e.length===0,errors:e}},j=(r,e)=>{let t={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return r.startsWith(t[e])},fe=(r,e)=>{if(typeof r!="number")return{isValid:!1,error:"Amount must be a number"};if(r<0)return{isValid:!1,error:"Amount must be non-negative"};let i={USD:50,EUR:50,GBP:30,JPY:50,CAD:50,AUD:50}[e.toUpperCase()]||50;return r<i?{isValid:!1,error:`Amount must be at least ${i} ${e.toLowerCase()} cents`}:{isValid:!0}},Pe=r=>{let e=[],t=r.number.replace(/\s/g,"");!t||t.length<13||t.length>19?e.push("Card number must be between 13 and 19 digits"):rt(t)||e.push("Invalid card number"),(!r.expMonth||r.expMonth<1||r.expMonth>12)&&e.push("Expiration month must be between 1 and 12");let i=new Date().getFullYear();return(!r.expYear||r.expYear<i||r.expYear>i+20)&&e.push("Invalid expiration year"),r.expMonth&&r.expYear&&new Date(r.expYear,r.expMonth-1,1)<new Date&&e.push("Card has expired"),(!r.cvc||r.cvc.length<3||r.cvc.length>4)&&e.push("CVC must be 3 or 4 digits"),{isValid:e.length===0,errors:e}},rt=r=>{let e=0,t=!1;for(let i=r.length-1;i>=0;i--){let n=parseInt(r.charAt(i),10);t&&(n*=2,n>9&&(n=n%10+1)),e+=n,t=!t}return e%10===0};var V=(r,e=H,t={})=>{let{showSymbol:i=!0,showCents:n=!0,locale:o="en-US"}=t,a=e.toUpperCase(),s=["JPY","KRW","VND","CLP"].includes(a),f=s?r:r/100;if(i)try{return new Intl.NumberFormat(o,{style:"currency",currency:a,minimumFractionDigits:n&&!s?2:0,maximumFractionDigits:n&&!s?2:0}).format(f)}catch{let l=ee[a]||a,p=n&&!s?f.toFixed(2):Math.round(f).toString();return`${l}${p}`}return n&&!s?f.toFixed(2):Math.round(f).toString()},te=r=>{let e=V(r.price,r.currency),t=r.intervalCount&&r.intervalCount>1?`${r.intervalCount} ${r.interval}s`:r.interval;return`${e}/${t}`},it=r=>({active:"Active",canceled:"Canceled",past_due:"Past Due",unpaid:"Unpaid",incomplete:"Incomplete",incomplete_expired:"Incomplete (Expired)",trialing:"Trial",ended:"Ended",all:"All"})[r]||r,be=(r,e={})=>{let{format:t="medium",locale:i="en-US",timeZone:n}=e,o=typeof r=="string"||typeof r=="number"?new Date(r):r,a={timeZone:n};switch(t){case"short":a.dateStyle="short";break;case"medium":a.dateStyle="medium";break;case"long":a.dateStyle="long";break;case"full":a.dateStyle="full";break}try{return new Intl.DateTimeFormat(i,a).format(o)}catch{return o.toLocaleDateString()}},nt=(r,e={})=>{let{locale:t="en-US",numeric:i="auto"}=e,n=typeof r=="string"||typeof r=="number"?new Date(r):r,a=Math.floor((new Date().getTime()-n.getTime())/1e3);try{let s=new Intl.RelativeTimeFormat(t,{numeric:i});return Math.abs(a)<60?s.format(-a,"second"):Math.abs(a)<3600?s.format(-Math.floor(a/60),"minute"):Math.abs(a)<86400?s.format(-Math.floor(a/3600),"hour"):Math.abs(a)<2592e3?s.format(-Math.floor(a/86400),"day"):Math.abs(a)<31536e3?s.format(-Math.floor(a/2592e3),"month"):s.format(-Math.floor(a/31536e3),"year")}catch{if(Math.abs(a)<60)return"just now";if(Math.abs(a)<3600){let s=Math.floor(Math.abs(a)/60);return a<0?`in ${s} minutes`:`${s} minutes ago`}else if(Math.abs(a)<86400){let s=Math.floor(Math.abs(a)/3600);return a<0?`in ${s} hours`:`${s} hours ago`}else{let s=Math.floor(Math.abs(a)/86400);return a<0?`in ${s} days`:`${s} days ago`}}},ot=(r,e=1)=>({day:e===1?"daily":`every ${e} days`,week:e===1?"weekly":`every ${e} weeks`,month:e===1?"monthly":`every ${e} months`,year:e===1?"yearly":`every ${e} years`})[r]||r,re=r=>r===0?"No trial":r===1?"1 day trial":r<7?`${r} days trial`:r===7?"1 week trial":r<30?`${Math.floor(r/7)} weeks trial`:r===30?"1 month trial":`${Math.floor(r/30)} months trial`,st=(r,e)=>r.length<=e?r:`${r.substring(0,e-3)}...`,Se=r=>({visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover",jcb:"JCB",diners:"Diners Club",unionpay:"UnionPay"})[r.toLowerCase()]||r,at=r=>r.type==="card"&&r.card?`${Se(r.card.brand)} \u2022\u2022\u2022\u2022 ${r.card.last4}`:r.type==="bank_account"&&r.bankAccount?`${r.bankAccount.bankName||"Bank"} \u2022\u2022\u2022\u2022 ${r.bankAccount.last4}`:r.type,ie=(r,e,t={})=>{let{inclusive:i=!1,roundTo:n=2}=t,o,a,s;i?(s=r,o=r/(1+e/100),a=r-o):(o=r,a=r*(e/100),s=r+a);let f=Math.pow(10,n);return{subtotal:Math.round(o*f)/f,tax:Math.round(a*f)/f,total:Math.round(s*f)/f}},ye=r=>`${r.toFixed(2)}%`,Ee=(r,e,t=H,i={})=>{let{inclusive:n=!1,showBreakdown:o=!1,locale:a="en-US"}=i,s=ie(r,e,{inclusive:n});if(o){let f=V(s.subtotal,t,{locale:a}),l=V(s.tax,t,{locale:a}),p=V(s.total,t,{locale:a});return`${f} + ${l} tax = ${p}`}return V(s.total,t,{locale:a})};var he=r=>{let e=[],t=[];return r.stripePublishableKey?r.stripePublishableKey.startsWith("pk_")||e.push('STRIPE_PUBLISHABLE_KEY must start with "pk_"'):e.push("STRIPE_PUBLISHABLE_KEY is required"),r.environment?["development","production"].includes(r.environment)||e.push('Environment must be either "development" or "production"'):e.push("Environment must be specified (development or production)"),r.environment==="production"&&(r.stripePublishableKey?.includes("test")&&t.push("Using test keys in production environment"),r.appUrl?r.appUrl.startsWith("https://")||t.push("APP_URL should use HTTPS in production"):t.push("APP_URL should be set in production for proper redirects")),typeof window>"u"&&(r.stripeSecretKey?r.stripeSecretKey.startsWith("sk_")||e.push('STRIPE_SECRET_KEY must start with "sk_"'):t.push("STRIPE_SECRET_KEY is recommended for server-side operations"),r.stripeWebhookSecret?r.stripeWebhookSecret.startsWith("whsec_")||e.push('STRIPE_WEBHOOK_SECRET must start with "whsec_"'):t.push("STRIPE_WEBHOOK_SECRET is recommended for webhook verification")),{isValid:e.length===0,errors:e,warnings:t}},ge=()=>{let r=typeof window>"u",e={stripePublishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY||"",environment:process.env.NODE_ENV||"development",appUrl:process.env.NEXT_PUBLIC_APP_URL};return r&&(e.stripeSecretKey=process.env.STRIPE_SECRET_KEY,e.stripeWebhookSecret=process.env.STRIPE_WEBHOOK_SECRET),e},ct=()=>{let r=ge(),e=he(r);if(!e.isValid&&(console.error("\u274C Environment validation failed:"),e.errors.forEach(t=>console.error(` - ${t}`)),typeof window>"u"))throw new Error(`Environment validation failed: ${e.errors.join(", ")}`);return e.warnings.length>0&&(console.warn("\u26A0\uFE0F Environment warnings:"),e.warnings.forEach(t=>console.warn(` - ${t}`))),e},ut=()=>process.env.NODE_ENV==="development",lt=()=>process.env.NODE_ENV==="production",mt=()=>typeof window>"u",dt=()=>typeof window<"u";var K=class{config;constructor(e){this.config=e}handleError(e,t="UNKNOWN_ERROR"){if(e instanceof c)return e;let i="An unknown error occurred",n,o;return typeof e=="object"&&e!==null&&("message"in e&&typeof e.message=="string"&&(i=e.message),"code"in e&&typeof e.code=="string"&&(n=e.code),o={...e}),new c(t,i,n,o)}};var Ce=$e(require("stripe")),Y=class extends K{name="stripe";stripeClient;constructor(e){if(super(e),!e.stripeConfig?.publishableKey)throw new c("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new c("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new Ce.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"})}async initialize(){console.log("StripePaymentProvider initialized (server-side)")}async createCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.create({payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"payment",success_url:e.successUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:e.cancelUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,customer_email:e.customerEmail,allow_promotion_codes:e.allowPromotionCodes,metadata:e.metadata});if(!t.url)throw new c("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createCustomer(e){try{let t=await this.stripeClient.customers.create({email:e.email,name:e.name,metadata:e.metadata});return{id:t.id,email:t.email||e.email,name:t.name||e.name,phone:null,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:null,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCustomer(e){try{let t=await this.stripeClient.customers.retrieve(e);return t.deleted?null:{id:t.id,email:t.email||"",name:t.name||void 0,phone:t.phone||void 0,stripeCustomerId:t.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:t.invoice_settings?.default_payment_method?.toString()||void 0,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async createSubscription(e){try{let t=await this.stripeClient.subscriptions.create({customer:e.customerId,items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(i=>({price:i.priceId,quantity:i.quantity||1})),trial_period_days:e.trialPeriodDays,metadata:e.metadata,expand:["latest_invoice.payment_intent"]});return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async cancelSubscription(e){try{await this.stripeClient.subscriptions.cancel(e)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async reactivateSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);if(t.status==="canceled"&&t.cancel_at_period_end)await this.stripeClient.subscriptions.update(e,{cancel_at_period_end:!1});else throw new c("VALIDATION_ERROR","Subscription cannot be reactivated.")}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async retrieveCheckoutSession(e){try{let t=await this.stripeClient.checkout.sessions.retrieve(e);if(!t.url)throw new c("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:t.id,url:t.url,status:t.status,amountTotal:t.amount_total||void 0,currency:t.currency||void 0,customerEmail:t.customer_details?.email||void 0,subscriptionId:t.subscription?.toString()||void 0}}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async listSubscriptions(e,t){try{return(await this.stripeClient.subscriptions.list({customer:e,status:t==="all"?void 0:t})).data.map(this.mapStripeSubscriptionToSubscription)}catch(i){throw this.handleError(i,"NETWORK_ERROR")}}async retrieveSubscription(e){try{let t=await this.stripeClient.subscriptions.retrieve(e);return this.mapStripeSubscriptionToSubscription(t)}catch(t){throw this.handleError(t,"NETWORK_ERROR")}}async updateSubscription(e,t){try{let i=await this.stripeClient.subscriptions.retrieve(e),n=t.items?t.items.map(a=>({id:i.items.data.find(s=>s.price?.id===a.priceId)?.id,price:a.priceId,quantity:a.quantity||1})):void 0,o=await this.stripeClient.subscriptions.update(e,{items:n,metadata:t.metadata});return this.mapStripeSubscriptionToSubscription(o)}catch(i){throw this.handleError(i,"NETWORK_ERROR")}}mapStripeSubscriptionToSubscription(e){return{id:e.id,customerId:e.customer.toString(),status:e.status,items:e.items.data.map(t=>({id:t.id,priceId:t.price?.id||"",quantity:t.quantity||1})),currentPeriodStart:new Date(e.current_period_start*1e3),currentPeriodEnd:new Date(e.current_period_end*1e3),cancelAtPeriodEnd:e.cancel_at_period_end,trialStart:e.trial_start?new Date(e.trial_start*1e3):void 0,trialEnd:e.trial_end?new Date(e.trial_end*1e3):void 0,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}};var G=class extends K{name="MockPaymentProvider";customers=[];subscriptions=[];nextCustomerId=1;nextSubscriptionId=1;constructor(e){super({...e,provider:"mock"}),console.log("MockPaymentProvider initialized")}async initialize(){console.log("MockPaymentProvider initialized")}async createCheckoutSession(e){return console.log("Mock: createCheckoutSession",e),{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"open"}}async retrieveCheckoutSession(e){if(console.log("Mock: retrieveCheckoutSession",e),e==="mock_cs_123")return{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"complete"};throw new c("CUSTOMER_NOT_FOUND",`Mock checkout session ${e} not found`)}async createCustomer(e){console.log("Mock: createCustomer",e);let t={id:`mock_cus_${this.nextCustomerId++}`,email:e.email,name:e.name||null,phone:e.phone||null,stripeCustomerId:null,subscriptions:[],defaultPaymentMethodId:null,paymentMethods:[],metadata:e.metadata||{},created:new Date,updated:new Date};return this.customers.push(t),t}async retrieveCustomer(e){console.log("Mock: retrieveCustomer",e);let t=this.customers.find(i=>i.id===e);if(!t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t}async updateCustomer(e,t){console.log("Mock: updateCustomer",e,t);let i=this.customers.find(n=>n.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.email&&(i.email=t.email),t.name&&(i.name=t.name),t.phone&&(i.phone=t.phone),t.metadata&&(i.metadata={...i.metadata,...t.metadata}),i.updated=new Date,i}async deleteCustomer(e){console.log("Mock: deleteCustomer",e);let t=this.customers.length;if(this.customers=this.customers.filter(i=>i.id!==e),this.customers.length===t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`)}async listPaymentMethods(e){console.log("Mock: listPaymentMethods",e);let t=this.customers.find(i=>i.id===e);if(!t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);return t.paymentMethods||[]}async attachPaymentMethod(e,t){console.log("Mock: attachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n={id:t,type:"card",card:{brand:"visa",last4:"4242",expMonth:12,expYear:2025,country:"US"},isDefault:!1,created:new Date};return i.paymentMethods.push(n),n}async detachPaymentMethod(e,t){console.log("Mock: detachPaymentMethod",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.paymentMethods.length;if(i.paymentMethods=i.paymentMethods.filter(o=>o.id!==t),i.paymentMethods.length===n)throw new c("CUSTOMER_NOT_FOUND",`Mock payment method ${t} not found for customer ${e}`)}async createSubscription(e){console.log("Mock: createSubscription",e);let t=this.customers.find(n=>n.id===e.customerId);if(!t)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e.customerId} not found`);let i={id:`mock_sub_${this.nextSubscriptionId++}`,customerId:e.customerId,status:"active",items:(e.items||(e.priceId?[{priceId:e.priceId,quantity:1}]:[])).map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1})),currentPeriodStart:new Date,currentPeriodEnd:new Date(Date.now()+720*60*60*1e3),cancelAtPeriodEnd:!1,created:new Date,updated:new Date};return this.subscriptions.push(i),t.subscriptions.push(i),i}async retrieveSubscription(e){console.log("Mock: retrieveSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t}async updateSubscription(e,t){console.log("Mock: updateSubscription",e,t);let i=this.subscriptions.find(n=>n.id===e);if(!i)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);return t.cancelAtPeriodEnd!==void 0&&(i.cancelAtPeriodEnd=t.cancelAtPeriodEnd,i.status=t.cancelAtPeriodEnd?"canceled":"active"),t.items&&(i.items=t.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),i.updated=new Date,i}async cancelSubscription(e){console.log("Mock: cancelSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="canceled",t.cancelAtPeriodEnd=!0,t.updated=new Date}async reactivateSubscription(e){console.log("Mock: reactivateSubscription",e);let t=this.subscriptions.find(i=>i.id===e);if(!t)throw new c("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${e} not found`);t.status="active",t.cancelAtPeriodEnd=!1,t.updated=new Date}async listSubscriptions(e,t){console.log("Mock: listSubscriptions",e,t);let i=this.customers.find(o=>o.id===e);if(!i)throw new c("CUSTOMER_NOT_FOUND",`Mock customer ${e} not found`);let n=i.subscriptions;return t&&t!=="all"&&(n=n.filter(o=>o.status===t)),n}};var R=class{static create(e){switch(e.provider){case"stripe":return new Y(e);case"paypal":throw new c("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new c("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new G(e);default:throw new c("CONFIGURATION_ERROR",`Unsupported payment provider: ${e.provider}`)}}static autodetect(){if(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&process.env.STRIPE_SECRET_KEY)return{provider:"stripe",publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,environment:process.env.NODE_ENV==="production"?"production":"development",stripeConfig:{publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}};if(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&process.env.PAYPAL_CLIENT_SECRET)return{provider:"paypal",publishableKey:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,environment:process.env.NODE_ENV==="production"?"production":"development",paypalConfig:{clientId:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,clientSecret:process.env.PAYPAL_CLIENT_SECRET,environment:process.env.NODE_ENV==="production"?"production":"sandbox",currency:process.env.PAYPAL_CURRENCY||"USD"}};if(process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID&&typeof window<"u"&&window.ApplePaySession)return{provider:"applepay",environment:process.env.NODE_ENV==="production"?"production":"development",applePayConfig:{merchantId:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID,merchantName:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME||"Your Store",countryCode:process.env.NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE||"US",currencyCode:process.env.NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE||"USD",environment:process.env.NODE_ENV==="production"?"production":"sandbox"}};if(process.env.NODE_ENV!=="production"||process.env.VERCEL_ENV==="preview")return console.warn("No payment provider detected, defaulting to MockPaymentProvider for development/preview environment."),{provider:"mock",environment:"development"};throw new c("CONFIGURATION_ERROR","Could not auto-detect payment provider. Please provide explicit configuration.")}static getAvailableProviders(){let e=[];return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&e.push("stripe"),process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&e.push("paypal"),typeof window<"u"&&window.ApplePaySession?.canMakePayments()&&e.push("applepay"),process.env.NODE_ENV!=="production"&&e.push("mock"),e}static createMultiple(e){return e.map(t=>this.create(t))}};var T=require("react");var Re=require("zustand"),_e=require("zustand/middleware/immer");var ve={customer:null,subscriptions:[],activeSubscription:null,loading:!1,error:null,initialized:!1,config:null,isLoading:!1,isError:!1},Ie=(0,Re.create)()((0,_e.immer)((r,e)=>({...ve,get isLoading(){return e().loading},get isError(){return!!e().error},initialize:async t=>{r(i=>{i.loading=!0,i.error=null});try{let i;t?i=t:i=R.autodetect(),await R.create(i).initialize(),r(o=>{o.initialized=!0,o.loading=!1,o.config=i})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to initialize payments provider.";n.error=new c("CONFIGURATION_ERROR",o),n.loading=!1}),i}},createCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCustomer(t);return r(o=>{o.customer=n,o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},createCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create checkout session.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},retrieveCheckoutSession:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCheckoutSession(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve checkout session.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},createSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).createSubscription(t);return await e().refreshSubscriptions(e().customer?.id||""),r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to create subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},cancelSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await R.create(e().config).cancelSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to cancel subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},reactivateSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");await R.create(e().config).reactivateSubscription(t),await e().refreshSubscriptions(e().customer?.id||""),r(n=>{n.loading=!1})}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to reactivate subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},updateSubscription:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).updateSubscription(t,i);return await e().refreshSubscriptions(e().customer?.id||""),r(a=>{a.loading=!1}),o}catch(n){throw r(o=>{let a=n instanceof Error?n.message:"Failed to update subscription.";o.error=new c("NETWORK_ERROR",a),o.loading=!1}),n}},listSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).listSubscriptions(t,i);return r(a=>{a.subscriptions=o,a.loading=!1}),o}catch(n){throw r(o=>{let a=n instanceof Error?n.message:"Failed to list subscriptions.";o.error=new c("NETWORK_ERROR",a),o.loading=!1}),n}},retrieveSubscription:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveSubscription(t);return r(o=>{o.loading=!1}),n}catch(i){throw r(n=>{let o=i instanceof Error?i.message:"Failed to retrieve subscription.";n.error=new c("NETWORK_ERROR",o),n.loading=!1}),i}},refreshCustomer:async t=>{r(i=>{i.loading=!0,i.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let n=await R.create(e().config).retrieveCustomer(t);r(o=>{o.customer=n,o.loading=!1})}catch(i){r(n=>{let o=i instanceof Error?i.message:"Failed to refresh customer.";n.error=new c("NETWORK_ERROR",o),n.loading=!1})}},refreshSubscriptions:async(t,i)=>{r(n=>{n.loading=!0,n.error=null});try{if(!e().config)throw new c("CONFIGURATION_ERROR","Payments provider not initialized. Call initialize() first.");let o=await R.create(e().config).listSubscriptions(t,i),a=o.find(s=>s.status==="active"||s.status==="trialing")||null;r(s=>{s.subscriptions=o,s.activeSubscription=a,s.loading=!1})}catch(n){r(o=>{let a=n instanceof Error?n.message:"Failed to refresh subscriptions.";o.error=new c("NETWORK_ERROR",a),o.loading=!1})}},reset:()=>{r(t=>{Object.assign(t,ve)})}})));var Oe=require("react/jsx-runtime"),we=(0,T.createContext)(void 0),Ne=({children:r,config:e,onPaymentSuccess:t,onPaymentError:i})=>{let n=Ie(),{initialize:o,initialized:a,loading:s,error:f,customer:l,subscriptions:p,activeSubscription:w}=n,m=(0,T.useRef)(t),P=(0,T.useRef)(i);(0,T.useEffect)(()=>{m.current=t},[t]),(0,T.useEffect)(()=>{P.current=i},[i]),(0,T.useEffect)(()=>{!a&&!s&&!f&&o(e).catch(v=>{console.error("PaymentsProvider initialization failed:",v),P.current&&P.current(v)})},[a,s,f,e,o]);let d={config:n.config,initialized:a,loading:s,error:f,customer:l,subscriptions:p,activeSubscription:w,createCustomer:n.createCustomer,createCheckoutSession:n.createCheckoutSession,cancelSubscription:n.cancelSubscription,reactivateSubscription:n.reactivateSubscription,updateSubscription:n.updateSubscription,refreshCustomer:n.refreshCustomer,refreshSubscriptions:n.refreshSubscriptions,reset:n.reset};return(0,Oe.jsx)(we.Provider,{value:d,children:r})},$=()=>{let r=(0,T.useContext)(we);if(r===void 0)throw new Error("usePaymentsContext must be used within a PaymentsProvider");return r};var E=require("react");var Te=()=>{let[r,e]=(0,E.useState)(null),[t,i]=(0,E.useState)(null),[n,o]=(0,E.useState)(!1),[a,s]=(0,E.useState)(!1),[f,l]=(0,E.useState)(null),[p,w]=(0,E.useState)(null),[m,P]=(0,E.useState)([]),d=(0,E.useCallback)(b=>{l(b),console.error("Payments error:",b)},[]),v=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.listSubscriptions(b,u);P(N)}catch(N){throw d(N),N}finally{s(!1)}},[t,d]),F=(0,E.useCallback)(async b=>{s(!0),l(null);try{let u=b||R.autodetect(),N=R.create(u);e(u),i(N),o(!0)}catch(u){d(u)}finally{s(!1)}},[d]),h=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveCustomer(b);return w(u),u}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),k=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.createCustomer(b);return w(u),u}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),W=(0,E.useCallback)(async b=>{if(!t||!p)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.createSubscription({customerId:p.id,items:[{priceId:b.priceId,quantity:b.quantity}]});return await v(p.id),u}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),O=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.listSubscriptions(b,u);return P(N),N}catch(N){throw d(N),N}finally{s(!1)}},[t,d]),g=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveSubscription(b);return p?.id&&await v(p.id),u}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),A=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{return await t.createCheckoutSession(b)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),B=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{return await t.retrieveCheckoutSession(b)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),D=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{await t.cancelSubscription(b),p?.id&&await v(p.id)}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),I=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{await t.reactivateSubscription(b),p?.id&&await v(p.id)}catch(u){throw d(u),u}finally{s(!1)}},[t,p,d,v]),L=(0,E.useCallback)(async(b,u)=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let N=await t.updateSubscription(b,u);return p?.id&&await v(p.id),N}catch(N){throw d(N),N}finally{s(!1)}},[t,p,d,v]),z=(0,E.useCallback)(async b=>{if(!t)throw new c("PROVIDER_NOT_CONFIGURED",y.PROVIDER_NOT_CONFIGURED);s(!0),l(null);try{let u=await t.retrieveCustomer(b);w(u)}catch(u){throw d(u),u}finally{s(!1)}},[t,d]),Q=(0,E.useCallback)(()=>{e(null),i(null),o(!1),s(!1),l(null),w(null),P([])},[]),Ae=m.find(b=>b.status==="active"||b.status==="trialing")||null;return(0,E.useEffect)(()=>{},[]),{config:r,provider:t,initialized:n,loading:a,error:f,isLoading:a,isError:!!f,customer:p,subscriptions:m,activeSubscription:Ae,initialize:F,createCustomer:k,retrieveCustomer:h,createCheckoutSession:A,retrieveCheckoutSession:B,createSubscription:W,cancelSubscription:D,reactivateSubscription:I,listSubscriptions:O,retrieveSubscription:g,updateSubscription:L,refreshCustomer:z,refreshSubscriptions:v,reset:Q}};var De=require("react"),ke=require("@stripe/react-stripe-js");var U=require("react/jsx-runtime"),Ue=({priceId:r,customerId:e,customerEmail:t,successUrl:i=typeof window<"u"?`${window.location.origin}/success`:"/success",cancelUrl:n=typeof window<"u"?`${window.location.origin}/cancel`:"/cancel",children:o,className:a="",disabled:s=!1,allowPromotionCodes:f=!0,billingAddressCollection:l="auto",metadata:p,trialPeriodDays:w,onSuccess:m,onError:P,onLoading:d})=>{let v=(0,ke.useStripe)(),{initialized:F}=$(),[h,k]=(0,De.useState)(!1);return(0,U.jsx)("button",{onClick:async()=>{if(!v){let g=y.STRIPE_NOT_LOADED;P?.(g),console.error(g);return}if(!F){let g=y.PROVIDER_NOT_CONFIGURED;P?.(g),console.error(g);return}if(!j(r,"price")){let g=y.INVALID_PRICE_ID;P?.(g),console.error(g);return}if(e&&!j(e,"customer")){let g=y.INVALID_CUSTOMER_ID;P?.(g),console.error(g);return}k(!0),d?.(!0);try{let g=await fetch("/api/payments/create-checkout-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceId:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,allowPromotionCodes:f,billingAddressCollection:l,metadata:p,trialPeriodDays:w})});if(!g.ok){let D=await g.json().catch(()=>({error:"Network error"}));throw new Error(D.error||y.CHECKOUT_FAILED)}let{sessionId:A}=await g.json();if(!A)throw new Error("No session ID returned from server");let B=await v.redirectToCheckout({sessionId:A});if(B.error)throw new Error(B.error.message||y.CHECKOUT_FAILED);m?.()}catch(g){let A=g instanceof Error?g.message:y.CHECKOUT_FAILED;P?.(A),console.error("Checkout error:",g)}finally{k(!1),d?.(!1)}},disabled:!v||h||s||!F,className:`
2
- inline-flex items-center justify-center px-4 py-2
3
- border border-transparent text-sm font-medium rounded-md
4
- text-white bg-blue-600 hover:bg-blue-700
5
- focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500
6
- disabled:opacity-50 disabled:cursor-not-allowed
7
- transition-colors duration-200
8
- ${a}
9
- `,"aria-label":typeof o=="string"?o:"Checkout",children:h?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)("svg",{className:"animate-spin -ml-1 mr-3 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,U.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,U.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):o})};var C=require("react/jsx-runtime"),ne=({plans:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,className:o="",onCheckoutSuccess:a,onCheckoutError:s,showFeatures:f=!0,showTrialInfo:l=!0,layout:p="grid",maxColumns:w=3})=>{if(!r||r.length===0)return(0,C.jsx)("div",{className:"text-center py-8 text-gray-500",children:"No pricing plans available"});let m=Math.min(r.length,w),P=p==="grid"?`grid gap-6 ${m===1?"grid-cols-1":m===2?"grid-cols-1 md:grid-cols-2":"grid-cols-1 md:grid-cols-2 lg:grid-cols-3"}`:"space-y-6";return(0,C.jsx)("div",{className:`pricing-table ${o}`,children:(0,C.jsx)("div",{className:P,children:r.map(d=>(0,C.jsx)(pt,{plan:d,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,onCheckoutSuccess:()=>a?.(d),onCheckoutError:v=>s?.(d,v),showFeatures:f,showTrialInfo:l},d.id))})})},pt=({plan:r,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,onCheckoutSuccess:o,onCheckoutError:a,showFeatures:s=!0,showTrialInfo:f=!0})=>{let l=r.popular;return(0,C.jsxs)("div",{className:`
10
- relative bg-white rounded-lg shadow-lg overflow-hidden
11
- ${l?"ring-2 ring-blue-500 ring-opacity-50":"border border-gray-200"}
12
- transition-transform duration-200 hover:scale-105
13
- `,children:[l&&(0,C.jsx)("div",{className:"absolute top-0 left-0 right-0 bg-blue-500 text-white text-center py-2 text-sm font-medium",children:"Most Popular"}),(0,C.jsxs)("div",{className:`p-6 ${l?"pt-12":""}`,children:[(0,C.jsxs)("div",{className:"text-center mb-6",children:[(0,C.jsx)("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:r.name}),r.description&&(0,C.jsx)("p",{className:"text-gray-600 text-sm mb-4",children:r.description}),(0,C.jsx)("div",{className:"mb-4",children:(0,C.jsx)("span",{className:"text-3xl font-bold text-gray-900",children:te(r)})}),f&&r.trialPeriodDays&&r.trialPeriodDays>0&&(0,C.jsx)("div",{className:"text-sm text-green-600 font-medium",children:re(r.trialPeriodDays)})]}),s&&r.features&&r.features.length>0&&(0,C.jsx)("div",{className:"mb-6",children:(0,C.jsx)("ul",{className:"space-y-3",children:r.features.map((p,w)=>(0,C.jsxs)("li",{className:"flex items-start",children:[(0,C.jsx)("svg",{className:"flex-shrink-0 w-5 h-5 text-green-500 mt-0.5 mr-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,C.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),(0,C.jsx)("span",{className:"text-gray-700 text-sm",children:p})]},w))})}),(0,C.jsx)("div",{className:"mt-6",children:(0,C.jsx)(Ue,{priceId:r.stripePriceId,customerId:e,customerEmail:t,successUrl:i,cancelUrl:n,trialPeriodDays:r.trialPeriodDays,metadata:r.metadata,onSuccess:o,onError:a,className:`
14
- w-full justify-center py-3 px-4 text-base font-medium
15
- ${l?"bg-blue-600 hover:bg-blue-700 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-900 border border-gray-300"}
16
- `,children:"Get Started"})})]})]})};var J=require("react"),x=require("@stripe/react-stripe-js");var _=require("react/jsx-runtime"),Z=({clientSecret:r,customerId:e,customerEmail:t,amount:i,currency:n="usd",description:o,metadata:a,onSuccess:s,onError:f,onLoading:l,className:p="",showBillingDetails:w=!0,elementType:m="payment"})=>{let P=(0,x.useStripe)(),d=(0,x.useElements)(),{initialized:v}=$(),[F,h]=(0,J.useState)(!1),[k,W]=(0,J.useState)(t||""),[O,g]=(0,J.useState)({name:"",email:t||"",phone:"",address:{line1:"",line2:"",city:"",state:"",postal_code:"",country:"US"}}),A=async D=>{if(D.preventDefault(),!P||!d){let I=y.STRIPE_NOT_LOADED;f?.(I);return}if(!v){let I=y.PROVIDER_NOT_CONFIGURED;f?.(I);return}if(w&&k&&!X(k)){f?.("Please enter a valid email address");return}h(!0),l?.(!0);try{let I;if(m==="payment"&&r)I=await P.confirmPayment({elements:d,confirmParams:{return_url:window.location.href,receipt_email:k||O.email},redirect:"if_required"});else if(m==="card"){let L=d.getElement(x.CardElement);if(!L)throw new Error("Card element not found");if(r)I=await P.confirmCardPayment(r,{payment_method:{card:L,billing_details:w?{name:O.name||void 0,email:O.email||void 0,phone:O.phone||void 0,address:O.address.line1?O.address:void 0}:void 0}});else if(i){let z=await fetch("/api/payments/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:i,currency:n,customerId:e,description:o,metadata:a})});if(!z.ok)throw new Error("Failed to create payment intent");let{client_secret:Q}=await z.json();I=await P.confirmCardPayment(Q,{payment_method:{card:L,billing_details:w?{name:O.name||void 0,email:O.email||void 0,phone:O.phone||void 0,address:O.address.line1?O.address:void 0}:void 0}})}else throw new Error("Either clientSecret or amount is required")}if(I?.error)throw new Error(I.error.message||y.PAYMENT_FAILED);I?.paymentIntent?.status==="succeeded"&&s?.(I.paymentIntent)}catch(I){let L=I instanceof Error?I.message:y.PAYMENT_FAILED;f?.(L),console.error("Payment error:",I)}finally{h(!1),l?.(!1)}},B={style:{base:{fontSize:"16px",color:"#424770","::placeholder":{color:"#aab7c4"}},invalid:{color:"#9e2146"}}};return(0,_.jsxs)("form",{onSubmit:A,className:`payment-form ${p}`,children:[w&&(0,_.jsxs)("div",{className:"mb-6 space-y-4",children:[(0,_.jsxs)("div",{children:[(0,_.jsx)("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-1",children:"Email"}),(0,_.jsx)("input",{type:"email",id:"email",value:k,onChange:D=>{W(D.target.value),g(I=>({...I,email:D.target.value}))},className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"your@email.com",required:!0})]}),(0,_.jsxs)("div",{children:[(0,_.jsx)("label",{htmlFor:"name",className:"block text-sm font-medium text-gray-700 mb-1",children:"Full Name"}),(0,_.jsx)("input",{type:"text",id:"name",value:O.name,onChange:D=>g(I=>({...I,name:D.target.value})),className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"John Doe"})]})]}),(0,_.jsxs)("div",{className:"mb-6",children:[(0,_.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Payment Information"}),(0,_.jsx)("div",{className:"p-3 border border-gray-300 rounded-md",children:m==="payment"?(0,_.jsx)(x.PaymentElement,{}):(0,_.jsx)(x.CardElement,{options:B})})]}),(0,_.jsx)("button",{type:"submit",disabled:!P||F,className:"w-full bg-blue-600 text-white py-3 px-4 rounded-md font-medium hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200",children:F?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)("svg",{className:"animate-spin -ml-1 mr-3 h-4 w-4 text-white inline",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,_.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,_.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):`Pay ${i?`$${(i/100).toFixed(2)}`:""}`})]})};var xe=require("react"),S=require("react/jsx-runtime"),oe=({subscription:r,onSubscriptionChange:e,onCancel:t,className:i=""})=>{let[n,o]=(0,xe.useState)(!1),a=P=>new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(P),s=(P,d)=>new Intl.NumberFormat("en-US",{style:"currency",currency:d.toUpperCase()}).format(P/100),f=P=>{switch(P){case"active":return"#10b981";case"canceled":return"#ef4444";case"past_due":return"#f59e0b";case"unpaid":return"#ef4444";case"incomplete":return"#6b7280";default:return"#6b7280"}},l=P=>{switch(P){case"active":return"Active";case"canceled":return"Canceled";case"past_due":return"Past Due";case"unpaid":return"Unpaid";case"incomplete":return"Incomplete";default:return P}},p=async P=>{o(!0);try{await e(P)}finally{o(!1)}},w=async()=>{o(!0);try{await t()}finally{o(!1)}},m={container:{width:"100%"},card:{border:"1px solid #e5e7eb",borderRadius:"12px",padding:"2rem",background:"white",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},header:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"1.5rem"},info:{flex:1},planName:{fontSize:"1.5rem",fontWeight:700,color:"#1f2937",margin:"0 0 0.5rem 0"},details:{display:"flex",alignItems:"baseline",gap:"0.25rem"},amount:{fontSize:"1.25rem",fontWeight:600,color:"#3b82f6"},interval:{fontSize:"1rem",color:"#6b7280"},statusBadge:{padding:"0.5rem 1rem",borderRadius:"20px",color:"white",fontSize:"0.875rem",fontWeight:600},dates:{marginBottom:"2rem",padding:"1rem",background:"#f9fafb",borderRadius:"8px"},dateLabel:{fontSize:"0.875rem",color:"#6b7280",fontWeight:500},dateValue:{fontSize:"0.875rem",color:"#1f2937"},cancellationNotice:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",padding:"0.75rem",background:"#fef3c7",borderRadius:"6px",fontSize:"0.875rem",color:"#92400e"},actions:{display:"flex",gap:"1rem",flexWrap:"wrap"},button:{padding:"0.75rem 1.5rem",border:"none",borderRadius:"8px",fontWeight:600,fontSize:"0.875rem",cursor:"pointer",transition:"all 0.3s ease",flex:1,minWidth:"120px"},buttonPrimary:{background:"#3b82f6",color:"white"},buttonSecondary:{background:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db"},buttonDanger:{background:"#ef4444",color:"white"},buttonDisabled:{opacity:.6,cursor:"not-allowed"}};return(0,S.jsx)("div",{style:m.container,className:i,children:(0,S.jsxs)("div",{style:m.card,children:[(0,S.jsxs)("div",{style:m.header,children:[(0,S.jsxs)("div",{style:m.info,children:[(0,S.jsx)("h3",{style:m.planName,children:r.planName}),(0,S.jsxs)("div",{style:m.details,children:[(0,S.jsx)("span",{style:m.amount,children:s(r.amount,r.currency)}),(0,S.jsxs)("span",{style:m.interval,children:["/",r.interval]})]})]}),(0,S.jsx)("div",{children:(0,S.jsx)("span",{style:{...m.statusBadge,backgroundColor:f(r.status)},children:l(r.status)})})]}),(0,S.jsxs)("div",{style:m.dates,children:[(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{style:m.dateLabel,children:"Current period:"}),(0,S.jsxs)("div",{style:m.dateValue,children:[a(r.currentPeriodStart)," -"," ",a(r.currentPeriodEnd)]})]}),r.cancelAtPeriodEnd&&(0,S.jsxs)("div",{style:m.cancellationNotice,children:[(0,S.jsx)("span",{children:"\u26A0\uFE0F"}),(0,S.jsx)("span",{children:"Your subscription will be canceled at the end of the current period."})]})]}),(0,S.jsxs)("div",{style:m.actions,children:[r.status==="active"&&!r.cancelAtPeriodEnd&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)("button",{style:{...m.button,...m.buttonSecondary,...n?m.buttonDisabled:{}},onClick:()=>p("upgrade"),disabled:n,children:n?"Loading...":"Upgrade Plan"}),(0,S.jsx)("button",{style:{...m.button,...m.buttonSecondary,...n?m.buttonDisabled:{}},onClick:()=>p("downgrade"),disabled:n,children:n?"Loading...":"Downgrade Plan"}),(0,S.jsx)("button",{style:{...m.button,...m.buttonDanger,...n?m.buttonDisabled:{}},onClick:w,disabled:n,children:n?"Loading...":"Cancel Subscription"})]}),r.status==="active"&&r.cancelAtPeriodEnd&&(0,S.jsx)("button",{style:{...m.button,...m.buttonPrimary,...n?m.buttonDisabled:{}},onClick:()=>p("resume"),disabled:n,children:n?"Loading...":"Resume Subscription"}),r.status==="past_due"&&(0,S.jsx)("button",{style:{...m.button,...m.buttonPrimary,...n?m.buttonDisabled:{}},onClick:()=>p("resume"),disabled:n,children:n?"Loading...":"Update Payment Method"})]})]})})};0&&(module.exports={ACTIVE_STATUSES,BILLING_INTERVALS,CHECKOUT_MODE,CURRENCY_SYMBOLS,DEFAULT_CURRENCY,ERROR_MESSAGES,INACTIVE_STATUSES,INCOMPLETE_STATUSES,INVOICE_STATUS,MockPaymentProvider,PAYMENT_METHODS,PROBLEMATIC_STATUSES,PaymentErrorType,PaymentProviderFactory,PaymentsError,PaymentsProvider,PricingTable,STRIPE_API_VERSION,SUBSCRIPTION_STATUS,StripePaymentForm,StripePaymentProvider,SubscriptionManager,SubscriptionStatus,WEBHOOK_EVENTS,calculateTax,formatAmountWithTax,formatBillingInterval,formatCardBrand,formatCurrency,formatDate,formatPaymentMethodDisplay,formatPricingPlan,formatRelativeTime,formatSubscriptionStatus,formatTaxRate,formatTrialPeriod,getEnvironmentConfig,isActiveSubscription,isClient,isDevelopment,isInactiveSubscription,isIncompleteSubscription,isProblematicSubscription,isProduction,isServer,truncateText,usePayments,usePaymentsContext,validateAmount,validateCard,validateCurrentEnvironment,validateEmail,validateEnvironment,validatePaymentsConfig,validatePhoneNumber,validatePricingPlan,validateStripeId});
1
+ "use strict";var Y=Object.create;var S=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var H=(r,t)=>{for(var e in t)S(r,e,{get:t[e],enumerable:!0})},R=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $(t))!q.call(r,n)&&n!==e&&S(r,n,{get:()=>t[n],enumerable:!(i=V(t,n))||i.enumerable});return r};var X=(r,t,e)=>(e=r!=null?Y(W(r)):{},R(t||!r||!r.__esModule?S(e,"default",{value:r,enumerable:!0}):e,r)),G=r=>R(S({},"__esModule",{value:!0}),r);var It={};H(It,{ACTIVE_STATUSES:()=>v,BILLING_INTERVALS:()=>nt,CHECKOUT_MODE:()=>it,CURRENCY_SYMBOLS:()=>f,DEFAULT_CURRENCY:()=>h,ERROR_MESSAGES:()=>ot,INACTIVE_STATUSES:()=>y,INCOMPLETE_STATUSES:()=>O,INVOICE_STATUS:()=>rt,MockPaymentProvider:()=>_,PAYMENT_METHODS:()=>tt,PROBLEMATIC_STATUSES:()=>T,PaymentErrorType:()=>l,PaymentProviderFactory:()=>P,PaymentsError:()=>a,STRIPE_API_VERSION:()=>Q,SUBSCRIPTION_STATUS:()=>et,StripePaymentProvider:()=>b,SubscriptionStatus:()=>N,WEBHOOK_EVENTS:()=>st,calculateTax:()=>I,formatAmountWithTax:()=>x,formatBillingInterval:()=>lt,formatCardBrand:()=>M,formatCurrency:()=>m,formatDate:()=>k,formatPaymentMethodDisplay:()=>_t,formatPricingPlan:()=>pt,formatRelativeTime:()=>mt,formatSubscriptionStatus:()=>dt,formatTaxRate:()=>L,formatTrialPeriod:()=>Et,getEnvironmentConfig:()=>K,isActiveSubscription:()=>j,isClient:()=>ft,isDevelopment:()=>ht,isInactiveSubscription:()=>Z,isIncompleteSubscription:()=>J,isProblematicSubscription:()=>z,isProduction:()=>Pt,isServer:()=>Ct,truncateText:()=>bt,validateAmount:()=>A,validateCard:()=>U,validateCurrentEnvironment:()=>St,validateEmail:()=>g,validateEnvironment:()=>B,validatePaymentsConfig:()=>w,validatePhoneNumber:()=>at,validatePricingPlan:()=>D,validateStripeId:()=>ct});module.exports=G(It);var N=(d=>(d.ACTIVE="active",d.CANCELED="canceled",d.PAST_DUE="past_due",d.UNPAID="unpaid",d.INCOMPLETE="incomplete",d.INCOMPLETE_EXPIRED="incomplete_expired",d.TRIALING="trialing",d.ENDED="ended",d.ALL="all",d))(N||{}),v=["active","trialing"],y=["canceled","ended"],T=["past_due","unpaid"],O=["incomplete","incomplete_expired"],j=r=>v.includes(r),Z=r=>y.includes(r),z=r=>T.includes(r),J=r=>O.includes(r);var l=(u=>(u.CARD_DECLINED="CARD_DECLINED",u.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",u.CUSTOMER_NOT_FOUND="CUSTOMER_NOT_FOUND",u.SUBSCRIPTION_NOT_FOUND="SUBSCRIPTION_NOT_FOUND",u.NETWORK_ERROR="NETWORK_ERROR",u.CONFIGURATION_ERROR="CONFIGURATION_ERROR",u.WEBHOOK_ERROR="WEBHOOK_ERROR",u.VALIDATION_ERROR="VALIDATION_ERROR",u.PROVIDER_NOT_CONFIGURED="PROVIDER_NOT_CONFIGURED",u.UNKNOWN_ERROR="UNKNOWN_ERROR",u.INITIALIZATION_ERROR="INITIALIZATION_ERROR",u.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",u.NOT_FOUND="NOT_FOUND",u.INVALID_REQUEST="INVALID_REQUEST",u.API_ERROR="API_ERROR",u.PERMISSION_DENIED="PERMISSION_DENIED",u.WEBHOOK_VERIFICATION_FAILED="WEBHOOK_VERIFICATION_FAILED",u))(l||{}),a=class r extends Error{type;code;details;constructor(t,e,i,n){super(e),this.name="PaymentsError",this.type=t,this.code=i,this.details=n,Object.setPrototypeOf(this,r.prototype)}};var Q="2023-10-16",tt={CARD:"card",BANK_ACCOUNT:"bank_account",SEPA_DEBIT:"sepa_debit",IDEAL:"ideal",SOFORT:"sofort"},et={ACTIVE:"active",CANCELED:"canceled",PAST_DUE:"past_due",UNPAID:"unpaid",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",TRIALING:"trialing"},rt={DRAFT:"draft",OPEN:"open",PAID:"paid",UNCOLLECTIBLE:"uncollectible",VOID:"void"},it={PAYMENT:"payment",SUBSCRIPTION:"subscription",SETUP:"setup"},nt={DAY:"day",WEEK:"week",MONTH:"month",YEAR:"year"},f={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NZD:"NZ$"},h="USD",st={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"},ot={PROVIDER_NOT_CONFIGURED:"Payments provider is not properly configured",STRIPE_NOT_LOADED:"Stripe has not been loaded yet",INVALID_PRICE_ID:"Invalid price ID provided",INVALID_CUSTOMER_ID:"Invalid customer ID provided",CHECKOUT_FAILED:"Checkout session creation failed",PAYMENT_FAILED:"Payment processing failed",SUBSCRIPTION_NOT_FOUND:"Subscription not found",CUSTOMER_NOT_FOUND:"Customer not found"};var g=r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r),at=r=>/^\+?[\d\s-()]{10,}$/.test(r),w=r=>{let t=[];return r.publishableKey||t.push("publishableKey is required"),r.provider||t.push("provider is required"),r.provider!=="stripe"&&t.push("Only stripe provider is currently supported"),r.environment||t.push("environment is required"),r.environment&&!["development","production"].includes(r.environment)&&t.push('environment must be either "development" or "production"'),r.publishableKey&&!r.publishableKey.startsWith("pk_")&&t.push('publishableKey must start with "pk_"'),r.secretKey&&!r.secretKey.startsWith("sk_")&&t.push('secretKey must start with "sk_"'),r.webhookSecret&&!r.webhookSecret.startsWith("whsec_")&&t.push('webhookSecret must start with "whsec_"'),{isValid:t.length===0,errors:t}},D=r=>{let t=[];return r.id||t.push("id is required"),r.name||t.push("name is required"),(typeof r.price!="number"||r.price<0)&&t.push("price must be a non-negative number"),r.currency||t.push("currency is required"),r.interval||t.push("interval is required"),["day","week","month","year"].includes(r.interval)||t.push("interval must be one of: day, week, month, year"),r.stripePriceId||t.push("stripePriceId is required"),r.stripePriceId&&!r.stripePriceId.startsWith("price_")&&t.push('stripePriceId must start with "price_"'),Array.isArray(r.features)||t.push("features must be an array"),r.intervalCount&&(typeof r.intervalCount!="number"||r.intervalCount<1)&&t.push("intervalCount must be a positive number"),r.trialPeriodDays&&(typeof r.trialPeriodDays!="number"||r.trialPeriodDays<0)&&t.push("trialPeriodDays must be a non-negative number"),{isValid:t.length===0,errors:t}},ct=(r,t)=>{let e={customer:"cus_",subscription:"sub_",price:"price_",product:"prod_",payment_intent:"pi_"};return r.startsWith(e[t])},A=(r,t)=>{if(typeof r!="number")return{isValid:!1,error:"Amount must be a number"};if(r<0)return{isValid:!1,error:"Amount must be non-negative"};let i={USD:50,EUR:50,GBP:30,JPY:50,CAD:50,AUD:50}[t.toUpperCase()]||50;return r<i?{isValid:!1,error:`Amount must be at least ${i} ${t.toLowerCase()} cents`}:{isValid:!0}},U=r=>{let t=[],e=r.number.replace(/\s/g,"");!e||e.length<13||e.length>19?t.push("Card number must be between 13 and 19 digits"):ut(e)||t.push("Invalid card number"),(!r.expMonth||r.expMonth<1||r.expMonth>12)&&t.push("Expiration month must be between 1 and 12");let i=new Date().getFullYear();return(!r.expYear||r.expYear<i||r.expYear>i+20)&&t.push("Invalid expiration year"),r.expMonth&&r.expYear&&new Date(r.expYear,r.expMonth-1,1)<new Date&&t.push("Card has expired"),(!r.cvc||r.cvc.length<3||r.cvc.length>4)&&t.push("CVC must be 3 or 4 digits"),{isValid:t.length===0,errors:t}},ut=r=>{let t=0,e=!1;for(let i=r.length-1;i>=0;i--){let n=parseInt(r.charAt(i),10);e&&(n*=2,n>9&&(n=n%10+1)),t+=n,e=!e}return t%10===0};var m=(r,t=h,e={})=>{let{showSymbol:i=!0,showCents:n=!0,locale:c="en-US"}=e,s=t.toUpperCase(),o=["JPY","KRW","VND","CLP"].includes(s),p=o?r:r/100;if(i)try{return new Intl.NumberFormat(c,{style:"currency",currency:s,minimumFractionDigits:n&&!o?2:0,maximumFractionDigits:n&&!o?2:0}).format(p)}catch{let d=f[s]||s,C=n&&!o?p.toFixed(2):Math.round(p).toString();return`${d}${C}`}return n&&!o?p.toFixed(2):Math.round(p).toString()},pt=r=>{let t=m(r.price,r.currency),e=r.intervalCount&&r.intervalCount>1?`${r.intervalCount} ${r.interval}s`:r.interval;return`${t}/${e}`},dt=r=>({active:"Active",canceled:"Canceled",past_due:"Past Due",unpaid:"Unpaid",incomplete:"Incomplete",incomplete_expired:"Incomplete (Expired)",trialing:"Trial",ended:"Ended",all:"All"})[r]||r,k=(r,t={})=>{let{format:e="medium",locale:i="en-US",timeZone:n}=t,c=typeof r=="string"||typeof r=="number"?new Date(r):r,s={timeZone:n};switch(e){case"short":s.dateStyle="short";break;case"medium":s.dateStyle="medium";break;case"long":s.dateStyle="long";break;case"full":s.dateStyle="full";break}try{return new Intl.DateTimeFormat(i,s).format(c)}catch{return c.toLocaleDateString()}},mt=(r,t={})=>{let{locale:e="en-US",numeric:i="auto"}=t,n=typeof r=="string"||typeof r=="number"?new Date(r):r,s=Math.floor((new Date().getTime()-n.getTime())/1e3);try{let o=new Intl.RelativeTimeFormat(e,{numeric:i});return Math.abs(s)<60?o.format(-s,"second"):Math.abs(s)<3600?o.format(-Math.floor(s/60),"minute"):Math.abs(s)<86400?o.format(-Math.floor(s/3600),"hour"):Math.abs(s)<2592e3?o.format(-Math.floor(s/86400),"day"):Math.abs(s)<31536e3?o.format(-Math.floor(s/2592e3),"month"):o.format(-Math.floor(s/31536e3),"year")}catch{if(Math.abs(s)<60)return"just now";if(Math.abs(s)<3600){let o=Math.floor(Math.abs(s)/60);return s<0?`in ${o} minutes`:`${o} minutes ago`}else if(Math.abs(s)<86400){let o=Math.floor(Math.abs(s)/3600);return s<0?`in ${o} hours`:`${o} hours ago`}else{let o=Math.floor(Math.abs(s)/86400);return s<0?`in ${o} days`:`${o} days ago`}}},lt=(r,t=1)=>({day:t===1?"daily":`every ${t} days`,week:t===1?"weekly":`every ${t} weeks`,month:t===1?"monthly":`every ${t} months`,year:t===1?"yearly":`every ${t} years`})[r]||r,Et=r=>r===0?"No trial":r===1?"1 day trial":r<7?`${r} days trial`:r===7?"1 week trial":r<30?`${Math.floor(r/7)} weeks trial`:r===30?"1 month trial":`${Math.floor(r/30)} months trial`,bt=(r,t)=>r.length<=t?r:`${r.substring(0,t-3)}...`,M=r=>({visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover",jcb:"JCB",diners:"Diners Club",unionpay:"UnionPay"})[r.toLowerCase()]||r,_t=r=>r.type==="card"&&r.card?`${M(r.card.brand)} \u2022\u2022\u2022\u2022 ${r.card.last4}`:r.type==="bank_account"&&r.bankAccount?`${r.bankAccount.bankName||"Bank"} \u2022\u2022\u2022\u2022 ${r.bankAccount.last4}`:r.type,I=(r,t,e={})=>{let{inclusive:i=!1,roundTo:n=2}=e,c,s,o;i?(o=r,c=r/(1+t/100),s=r-c):(c=r,s=r*(t/100),o=r+s);let p=Math.pow(10,n);return{subtotal:Math.round(c*p)/p,tax:Math.round(s*p)/p,total:Math.round(o*p)/p}},L=r=>`${r.toFixed(2)}%`,x=(r,t,e=h,i={})=>{let{inclusive:n=!1,showBreakdown:c=!1,locale:s="en-US"}=i,o=I(r,t,{inclusive:n});if(c){let p=m(o.subtotal,e,{locale:s}),d=m(o.tax,e,{locale:s}),C=m(o.total,e,{locale:s});return`${p} + ${d} tax = ${C}`}return m(o.total,e,{locale:s})};var B=r=>{let t=[],e=[];return r.stripePublishableKey?r.stripePublishableKey.startsWith("pk_")||t.push('STRIPE_PUBLISHABLE_KEY must start with "pk_"'):t.push("STRIPE_PUBLISHABLE_KEY is required"),r.environment?["development","production"].includes(r.environment)||t.push('Environment must be either "development" or "production"'):t.push("Environment must be specified (development or production)"),r.environment==="production"&&(r.stripePublishableKey?.includes("test")&&e.push("Using test keys in production environment"),r.appUrl?r.appUrl.startsWith("https://")||e.push("APP_URL should use HTTPS in production"):e.push("APP_URL should be set in production for proper redirects")),typeof window>"u"&&(r.stripeSecretKey?r.stripeSecretKey.startsWith("sk_")||t.push('STRIPE_SECRET_KEY must start with "sk_"'):e.push("STRIPE_SECRET_KEY is recommended for server-side operations"),r.stripeWebhookSecret?r.stripeWebhookSecret.startsWith("whsec_")||t.push('STRIPE_WEBHOOK_SECRET must start with "whsec_"'):e.push("STRIPE_WEBHOOK_SECRET is recommended for webhook verification")),{isValid:t.length===0,errors:t,warnings:e}},K=()=>{let r=typeof window>"u",t={stripePublishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY||"",environment:process.env.NODE_ENV||"development",appUrl:process.env.NEXT_PUBLIC_APP_URL};return r&&(t.stripeSecretKey=process.env.STRIPE_SECRET_KEY,t.stripeWebhookSecret=process.env.STRIPE_WEBHOOK_SECRET),t},St=()=>{let r=K(),t=B(r);if(!t.isValid&&(console.error("\u274C Environment validation failed:"),t.errors.forEach(e=>console.error(` - ${e}`)),typeof window>"u"))throw new Error(`Environment validation failed: ${t.errors.join(", ")}`);return t.warnings.length>0&&(console.warn("\u26A0\uFE0F Environment warnings:"),t.warnings.forEach(e=>console.warn(` - ${e}`))),t},ht=()=>process.env.NODE_ENV==="development",Pt=()=>process.env.NODE_ENV==="production",Ct=()=>typeof window>"u",ft=()=>typeof window<"u";var E=class{config;constructor(t){this.config=t}handleError(t,e="UNKNOWN_ERROR"){if(t instanceof a)return t;let i="An unknown error occurred",n,c;return typeof t=="object"&&t!==null&&("message"in t&&typeof t.message=="string"&&(i=t.message),"code"in t&&typeof t.code=="string"&&(n=t.code),c={...t}),new a(e,i,n,c)}};var F=X(require("stripe")),b=class extends E{name="stripe";stripeClient;constructor(t){if(super(t),!t.stripeConfig?.publishableKey)throw new a("CONFIGURATION_ERROR","Stripe publishable key is missing in config.");if(!process.env.STRIPE_SECRET_KEY)throw new a("CONFIGURATION_ERROR","STRIPE_SECRET_KEY environment variable is not set.");this.stripeClient=new F.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"})}async initialize(){console.log("StripePaymentProvider initialized (server-side)")}async createCheckoutSession(t){try{let e=await this.stripeClient.checkout.sessions.create({payment_method_types:["card"],line_items:[{price:t.priceId,quantity:1}],mode:t.mode||"payment",success_url:t.successUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,cancel_url:t.cancelUrl||`${process.env.NEXT_PUBLIC_BASE_URL}/cancel`,customer_email:t.customerEmail,allow_promotion_codes:t.allowPromotionCodes,metadata:t.metadata});if(!e.url)throw new a("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:e.id,url:e.url,status:e.status,amountTotal:e.amount_total||void 0,currency:e.currency||void 0,customerEmail:e.customer_details?.email||void 0,subscriptionId:e.subscription?.toString()||void 0}}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async createCustomer(t){try{let e=await this.stripeClient.customers.create({email:t.email,name:t.name,metadata:t.metadata});return{id:e.id,email:e.email||t.email,name:e.name||t.name,phone:null,stripeCustomerId:e.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:null,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async retrieveCustomer(t){try{let e=await this.stripeClient.customers.retrieve(t);return e.deleted?null:{id:e.id,email:e.email||"",name:e.name||void 0,phone:e.phone||void 0,stripeCustomerId:e.id,subscriptions:[],paymentMethods:[],defaultPaymentMethodId:e.invoice_settings?.default_payment_method?.toString()||void 0,metadata:e.metadata,created:new Date(e.created*1e3),updated:new Date(e.created*1e3)}}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async createSubscription(t){try{let e=await this.stripeClient.subscriptions.create({customer:t.customerId,items:(t.items||(t.priceId?[{priceId:t.priceId,quantity:1}]:[])).map(i=>({price:i.priceId,quantity:i.quantity||1})),trial_period_days:t.trialPeriodDays,metadata:t.metadata,expand:["latest_invoice.payment_intent"]});return this.mapStripeSubscriptionToSubscription(e)}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async cancelSubscription(t){try{await this.stripeClient.subscriptions.cancel(t)}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async reactivateSubscription(t){try{let e=await this.stripeClient.subscriptions.retrieve(t);if(e.status==="canceled"&&e.cancel_at_period_end)await this.stripeClient.subscriptions.update(t,{cancel_at_period_end:!1});else throw new a("VALIDATION_ERROR","Subscription cannot be reactivated.")}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async retrieveCheckoutSession(t){try{let e=await this.stripeClient.checkout.sessions.retrieve(t);if(!e.url)throw new a("UNKNOWN_ERROR","Stripe checkout session URL is missing.");return{id:e.id,url:e.url,status:e.status,amountTotal:e.amount_total||void 0,currency:e.currency||void 0,customerEmail:e.customer_details?.email||void 0,subscriptionId:e.subscription?.toString()||void 0}}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async listSubscriptions(t,e){try{return(await this.stripeClient.subscriptions.list({customer:t,status:e==="all"?void 0:e})).data.map(this.mapStripeSubscriptionToSubscription)}catch(i){throw this.handleError(i,"NETWORK_ERROR")}}async retrieveSubscription(t){try{let e=await this.stripeClient.subscriptions.retrieve(t);return this.mapStripeSubscriptionToSubscription(e)}catch(e){throw this.handleError(e,"NETWORK_ERROR")}}async updateSubscription(t,e){try{let i=await this.stripeClient.subscriptions.retrieve(t),n=e.items?e.items.map(s=>({id:i.items.data.find(o=>o.price?.id===s.priceId)?.id,price:s.priceId,quantity:s.quantity||1})):void 0,c=await this.stripeClient.subscriptions.update(t,{items:n,metadata:e.metadata});return this.mapStripeSubscriptionToSubscription(c)}catch(i){throw this.handleError(i,"NETWORK_ERROR")}}mapStripeSubscriptionToSubscription(t){return{id:t.id,customerId:t.customer.toString(),status:t.status,items:t.items.data.map(e=>({id:e.id,priceId:e.price?.id||"",quantity:e.quantity||1})),currentPeriodStart:new Date(t.current_period_start*1e3),currentPeriodEnd:new Date(t.current_period_end*1e3),cancelAtPeriodEnd:t.cancel_at_period_end,trialStart:t.trial_start?new Date(t.trial_start*1e3):void 0,trialEnd:t.trial_end?new Date(t.trial_end*1e3):void 0,metadata:t.metadata,created:new Date(t.created*1e3),updated:new Date(t.created*1e3)}}};var _=class extends E{name="MockPaymentProvider";customers=[];subscriptions=[];nextCustomerId=1;nextSubscriptionId=1;constructor(t){super({...t,provider:"mock"}),console.log("MockPaymentProvider initialized")}async initialize(){console.log("MockPaymentProvider initialized")}async createCheckoutSession(t){return console.log("Mock: createCheckoutSession",t),{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"open"}}async retrieveCheckoutSession(t){if(console.log("Mock: retrieveCheckoutSession",t),t==="mock_cs_123")return{id:"mock_cs_123",clientSecret:"mock_client_secret",url:"https://mock-checkout.example.com/success",status:"complete"};throw new a("CUSTOMER_NOT_FOUND",`Mock checkout session ${t} not found`)}async createCustomer(t){console.log("Mock: createCustomer",t);let e={id:`mock_cus_${this.nextCustomerId++}`,email:t.email,name:t.name||null,phone:t.phone||null,stripeCustomerId:null,subscriptions:[],defaultPaymentMethodId:null,paymentMethods:[],metadata:t.metadata||{},created:new Date,updated:new Date};return this.customers.push(e),e}async retrieveCustomer(t){console.log("Mock: retrieveCustomer",t);let e=this.customers.find(i=>i.id===t);if(!e)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);return e}async updateCustomer(t,e){console.log("Mock: updateCustomer",t,e);let i=this.customers.find(n=>n.id===t);if(!i)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);return e.email&&(i.email=e.email),e.name&&(i.name=e.name),e.phone&&(i.phone=e.phone),e.metadata&&(i.metadata={...i.metadata,...e.metadata}),i.updated=new Date,i}async deleteCustomer(t){console.log("Mock: deleteCustomer",t);let e=this.customers.length;if(this.customers=this.customers.filter(i=>i.id!==t),this.customers.length===e)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`)}async listPaymentMethods(t){console.log("Mock: listPaymentMethods",t);let e=this.customers.find(i=>i.id===t);if(!e)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);return e.paymentMethods||[]}async attachPaymentMethod(t,e){console.log("Mock: attachPaymentMethod",t,e);let i=this.customers.find(c=>c.id===t);if(!i)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);let n={id:e,type:"card",card:{brand:"visa",last4:"4242",expMonth:12,expYear:2025,country:"US"},isDefault:!1,created:new Date};return i.paymentMethods.push(n),n}async detachPaymentMethod(t,e){console.log("Mock: detachPaymentMethod",t,e);let i=this.customers.find(c=>c.id===t);if(!i)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);let n=i.paymentMethods.length;if(i.paymentMethods=i.paymentMethods.filter(c=>c.id!==e),i.paymentMethods.length===n)throw new a("CUSTOMER_NOT_FOUND",`Mock payment method ${e} not found for customer ${t}`)}async createSubscription(t){console.log("Mock: createSubscription",t);let e=this.customers.find(n=>n.id===t.customerId);if(!e)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t.customerId} not found`);let i={id:`mock_sub_${this.nextSubscriptionId++}`,customerId:t.customerId,status:"active",items:(t.items||(t.priceId?[{priceId:t.priceId,quantity:1}]:[])).map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1})),currentPeriodStart:new Date,currentPeriodEnd:new Date(Date.now()+720*60*60*1e3),cancelAtPeriodEnd:!1,created:new Date,updated:new Date};return this.subscriptions.push(i),e.subscriptions.push(i),i}async retrieveSubscription(t){console.log("Mock: retrieveSubscription",t);let e=this.subscriptions.find(i=>i.id===t);if(!e)throw new a("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${t} not found`);return e}async updateSubscription(t,e){console.log("Mock: updateSubscription",t,e);let i=this.subscriptions.find(n=>n.id===t);if(!i)throw new a("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${t} not found`);return e.cancelAtPeriodEnd!==void 0&&(i.cancelAtPeriodEnd=e.cancelAtPeriodEnd,i.status=e.cancelAtPeriodEnd?"canceled":"active"),e.items&&(i.items=e.items.map(n=>({id:`mock_sub_item_${Math.random().toString(36).substring(7)}`,priceId:n.priceId,quantity:n.quantity||1}))),i.updated=new Date,i}async cancelSubscription(t){console.log("Mock: cancelSubscription",t);let e=this.subscriptions.find(i=>i.id===t);if(!e)throw new a("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${t} not found`);e.status="canceled",e.cancelAtPeriodEnd=!0,e.updated=new Date}async reactivateSubscription(t){console.log("Mock: reactivateSubscription",t);let e=this.subscriptions.find(i=>i.id===t);if(!e)throw new a("SUBSCRIPTION_NOT_FOUND",`Mock subscription ${t} not found`);e.status="active",e.cancelAtPeriodEnd=!1,e.updated=new Date}async listSubscriptions(t,e){console.log("Mock: listSubscriptions",t,e);let i=this.customers.find(c=>c.id===t);if(!i)throw new a("CUSTOMER_NOT_FOUND",`Mock customer ${t} not found`);let n=i.subscriptions;return e&&e!=="all"&&(n=n.filter(c=>c.status===e)),n}};var P=class{static create(t){switch(t.provider){case"stripe":return new b(t);case"paypal":throw new a("PROVIDER_NOT_CONFIGURED","PayPal provider is not yet available in this build");case"applepay":throw new a("PROVIDER_NOT_CONFIGURED","Apple Pay provider is not yet available in this build");case"mock":return new _(t);default:throw new a("CONFIGURATION_ERROR",`Unsupported payment provider: ${t.provider}`)}}static autodetect(){if(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&process.env.STRIPE_SECRET_KEY)return{provider:"stripe",publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,environment:process.env.NODE_ENV==="production"?"production":"development",stripeConfig:{publishableKey:process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}};if(process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&process.env.PAYPAL_CLIENT_SECRET)return{provider:"paypal",publishableKey:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,environment:process.env.NODE_ENV==="production"?"production":"development",paypalConfig:{clientId:process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,clientSecret:process.env.PAYPAL_CLIENT_SECRET,environment:process.env.NODE_ENV==="production"?"production":"sandbox",currency:process.env.PAYPAL_CURRENCY||"USD"}};if(process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID&&typeof window<"u"&&window.ApplePaySession)return{provider:"applepay",environment:process.env.NODE_ENV==="production"?"production":"development",applePayConfig:{merchantId:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID,merchantName:process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME||"Your Store",countryCode:process.env.NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE||"US",currencyCode:process.env.NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE||"USD",environment:process.env.NODE_ENV==="production"?"production":"sandbox"}};if(process.env.NODE_ENV!=="production"||process.env.VERCEL_ENV==="preview")return console.warn("No payment provider detected, defaulting to MockPaymentProvider for development/preview environment."),{provider:"mock",environment:"development"};throw new a("CONFIGURATION_ERROR","Could not auto-detect payment provider. Please provide explicit configuration.")}static getAvailableProviders(){let t=[];return process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY&&t.push("stripe"),process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID&&t.push("paypal"),typeof window<"u"&&window.ApplePaySession?.canMakePayments()&&t.push("applepay"),process.env.NODE_ENV!=="production"&&t.push("mock"),t}static createMultiple(t){return t.map(e=>this.create(e))}};0&&(module.exports={ACTIVE_STATUSES,BILLING_INTERVALS,CHECKOUT_MODE,CURRENCY_SYMBOLS,DEFAULT_CURRENCY,ERROR_MESSAGES,INACTIVE_STATUSES,INCOMPLETE_STATUSES,INVOICE_STATUS,MockPaymentProvider,PAYMENT_METHODS,PROBLEMATIC_STATUSES,PaymentErrorType,PaymentProviderFactory,PaymentsError,STRIPE_API_VERSION,SUBSCRIPTION_STATUS,StripePaymentProvider,SubscriptionStatus,WEBHOOK_EVENTS,calculateTax,formatAmountWithTax,formatBillingInterval,formatCardBrand,formatCurrency,formatDate,formatPaymentMethodDisplay,formatPricingPlan,formatRelativeTime,formatSubscriptionStatus,formatTaxRate,formatTrialPeriod,getEnvironmentConfig,isActiveSubscription,isClient,isDevelopment,isInactiveSubscription,isIncompleteSubscription,isProblematicSubscription,isProduction,isServer,truncateText,validateAmount,validateCard,validateCurrentEnvironment,validateEmail,validateEnvironment,validatePaymentsConfig,validatePhoneNumber,validatePricingPlan,validateStripeId});
17
2
  //# sourceMappingURL=index.js.map