@stripe-sdk/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1800 @@
1
+ 'use strict';
2
+
3
+ var Stripe = require('stripe');
4
+ var react = require('react');
5
+ var stripeJs = require('@stripe/stripe-js');
6
+ var reactStripeJs = require('@stripe/react-stripe-js');
7
+ var jsxRuntime = require('react/jsx-runtime');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var Stripe__default = /*#__PURE__*/_interopDefault(Stripe);
12
+
13
+ // src/server/stripe-client.ts
14
+ var stripeInstance = null;
15
+ var currentConfig = null;
16
+ function initStripe(config) {
17
+ currentConfig = config;
18
+ stripeInstance = new Stripe__default.default(config.secretKey, {
19
+ apiVersion: config.apiVersion ?? "2025-01-27.acacia",
20
+ appInfo: config.appInfo ?? {
21
+ name: "@stripe-sdk/core",
22
+ version: "1.0.0"
23
+ }
24
+ });
25
+ return stripeInstance;
26
+ }
27
+ function getStripe() {
28
+ if (!stripeInstance) {
29
+ throw new Error(
30
+ "[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first."
31
+ );
32
+ }
33
+ return stripeInstance;
34
+ }
35
+ function getConfig() {
36
+ if (!currentConfig) {
37
+ throw new Error(
38
+ "[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first."
39
+ );
40
+ }
41
+ return currentConfig;
42
+ }
43
+
44
+ // src/utils/errors.ts
45
+ function handleStripeError(error) {
46
+ if (error?.type) {
47
+ const stripeError = error;
48
+ return {
49
+ data: null,
50
+ error: {
51
+ message: stripeError.message,
52
+ type: stripeError.type,
53
+ code: stripeError.code,
54
+ statusCode: stripeError.statusCode
55
+ }
56
+ };
57
+ }
58
+ return {
59
+ data: null,
60
+ error: {
61
+ message: error instanceof Error ? error.message : "An unknown error occurred",
62
+ type: "sdk_error"
63
+ }
64
+ };
65
+ }
66
+ function success(data) {
67
+ return { data, error: null };
68
+ }
69
+
70
+ // src/server/payments/index.ts
71
+ async function createPaymentIntent(input) {
72
+ try {
73
+ const stripe = getStripe();
74
+ const paymentIntent = await stripe.paymentIntents.create({
75
+ amount: input.amount,
76
+ currency: input.currency,
77
+ customer: input.customerId,
78
+ payment_method: input.paymentMethodId,
79
+ metadata: input.metadata,
80
+ description: input.description,
81
+ receipt_email: input.receiptEmail,
82
+ setup_future_usage: input.setupFutureUsage,
83
+ automatic_payment_methods: input.automaticPaymentMethods === false || input.paymentMethodId ? void 0 : { enabled: true },
84
+ return_url: input.returnUrl
85
+ });
86
+ return success(paymentIntent);
87
+ } catch (error) {
88
+ return handleStripeError(error);
89
+ }
90
+ }
91
+ async function retrievePaymentIntent(paymentIntentId) {
92
+ try {
93
+ const stripe = getStripe();
94
+ const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
95
+ return success(paymentIntent);
96
+ } catch (error) {
97
+ return handleStripeError(error);
98
+ }
99
+ }
100
+ async function confirmPaymentIntent(input) {
101
+ try {
102
+ const stripe = getStripe();
103
+ const paymentIntent = await stripe.paymentIntents.confirm(input.paymentIntentId, {
104
+ payment_method: input.paymentMethodId,
105
+ return_url: input.returnUrl
106
+ });
107
+ return success(paymentIntent);
108
+ } catch (error) {
109
+ return handleStripeError(error);
110
+ }
111
+ }
112
+ async function cancelPaymentIntent(paymentIntentId) {
113
+ try {
114
+ const stripe = getStripe();
115
+ const paymentIntent = await stripe.paymentIntents.cancel(paymentIntentId);
116
+ return success(paymentIntent);
117
+ } catch (error) {
118
+ return handleStripeError(error);
119
+ }
120
+ }
121
+ async function listPaymentIntents(input) {
122
+ try {
123
+ const stripe = getStripe();
124
+ const paymentIntents = await stripe.paymentIntents.list({
125
+ limit: input?.limit ?? 10,
126
+ starting_after: input?.startingAfter,
127
+ ending_before: input?.endingBefore,
128
+ customer: input?.customerId
129
+ });
130
+ return success(paymentIntents);
131
+ } catch (error) {
132
+ return handleStripeError(error);
133
+ }
134
+ }
135
+ async function createCheckoutSession(input) {
136
+ try {
137
+ const stripe = getStripe();
138
+ const session = await stripe.checkout.sessions.create({
139
+ mode: input.mode,
140
+ line_items: input.lineItems.map((item) => ({
141
+ price: item.priceId,
142
+ quantity: item.quantity
143
+ })),
144
+ success_url: input.successUrl,
145
+ cancel_url: input.cancelUrl,
146
+ customer: input.customerId,
147
+ customer_email: input.customerEmail,
148
+ metadata: input.metadata,
149
+ allow_promotion_codes: input.allowPromotionCodes,
150
+ shipping_address_collection: input.shippingAddressCollection ? { allowed_countries: input.shippingAddressCollection.allowedCountries } : void 0,
151
+ billing_address_collection: input.billingAddressCollection,
152
+ subscription_data: input.trialPeriodDays ? { trial_period_days: input.trialPeriodDays } : void 0,
153
+ tax_id_collection: input.taxIdCollection ? { enabled: true } : void 0,
154
+ automatic_tax: input.automaticTax ? { enabled: true } : void 0,
155
+ locale: input.locale
156
+ });
157
+ return success(session);
158
+ } catch (error) {
159
+ return handleStripeError(error);
160
+ }
161
+ }
162
+ async function retrieveCheckoutSession(sessionId) {
163
+ try {
164
+ const stripe = getStripe();
165
+ const session = await stripe.checkout.sessions.retrieve(sessionId, {
166
+ expand: ["line_items", "payment_intent", "subscription"]
167
+ });
168
+ return success(session);
169
+ } catch (error) {
170
+ return handleStripeError(error);
171
+ }
172
+ }
173
+ async function listCheckoutSessions(input) {
174
+ try {
175
+ const stripe = getStripe();
176
+ const sessions = await stripe.checkout.sessions.list({
177
+ limit: input?.limit ?? 10,
178
+ starting_after: input?.startingAfter,
179
+ ending_before: input?.endingBefore
180
+ });
181
+ return success(sessions);
182
+ } catch (error) {
183
+ return handleStripeError(error);
184
+ }
185
+ }
186
+ async function createPaymentLink(input) {
187
+ try {
188
+ const stripe = getStripe();
189
+ const paymentLink = await stripe.paymentLinks.create({
190
+ line_items: input.lineItems.map((item) => ({
191
+ price: item.priceId,
192
+ quantity: item.quantity,
193
+ adjustable_quantity: item.adjustableQuantity ? {
194
+ enabled: item.adjustableQuantity.enabled,
195
+ minimum: item.adjustableQuantity.minimum,
196
+ maximum: item.adjustableQuantity.maximum
197
+ } : void 0
198
+ })),
199
+ metadata: input.metadata,
200
+ after_completion: input.afterCompletion ? {
201
+ type: input.afterCompletion.type,
202
+ redirect: input.afterCompletion.redirectUrl ? { url: input.afterCompletion.redirectUrl } : void 0
203
+ } : void 0,
204
+ allow_promotion_codes: input.allowPromotionCodes,
205
+ automatic_tax: input.automaticTax ? { enabled: true } : void 0,
206
+ billing_address_collection: input.billingAddressCollection,
207
+ shipping_address_collection: input.shippingAddressCollection ? { allowed_countries: input.shippingAddressCollection.allowedCountries } : void 0
208
+ });
209
+ return success(paymentLink);
210
+ } catch (error) {
211
+ return handleStripeError(error);
212
+ }
213
+ }
214
+ async function retrievePaymentLink(paymentLinkId) {
215
+ try {
216
+ const stripe = getStripe();
217
+ const paymentLink = await stripe.paymentLinks.retrieve(paymentLinkId);
218
+ return success(paymentLink);
219
+ } catch (error) {
220
+ return handleStripeError(error);
221
+ }
222
+ }
223
+ async function createSetupIntent(input) {
224
+ try {
225
+ const stripe = getStripe();
226
+ const setupIntent = await stripe.setupIntents.create({
227
+ customer: input.customerId,
228
+ payment_method_types: input.paymentMethodTypes,
229
+ usage: input.usage,
230
+ metadata: input.metadata
231
+ });
232
+ return success(setupIntent);
233
+ } catch (error) {
234
+ return handleStripeError(error);
235
+ }
236
+ }
237
+ async function retrieveSetupIntent(setupIntentId) {
238
+ try {
239
+ const stripe = getStripe();
240
+ const setupIntent = await stripe.setupIntents.retrieve(setupIntentId);
241
+ return success(setupIntent);
242
+ } catch (error) {
243
+ return handleStripeError(error);
244
+ }
245
+ }
246
+ async function listPaymentMethods(customerId, type) {
247
+ try {
248
+ const stripe = getStripe();
249
+ const paymentMethods = await stripe.paymentMethods.list({
250
+ customer: customerId,
251
+ type: type ?? "card"
252
+ });
253
+ return success(paymentMethods);
254
+ } catch (error) {
255
+ return handleStripeError(error);
256
+ }
257
+ }
258
+ async function attachPaymentMethod(paymentMethodId, customerId) {
259
+ try {
260
+ const stripe = getStripe();
261
+ const paymentMethod = await stripe.paymentMethods.attach(paymentMethodId, {
262
+ customer: customerId
263
+ });
264
+ return success(paymentMethod);
265
+ } catch (error) {
266
+ return handleStripeError(error);
267
+ }
268
+ }
269
+ async function detachPaymentMethod(paymentMethodId) {
270
+ try {
271
+ const stripe = getStripe();
272
+ const paymentMethod = await stripe.paymentMethods.detach(paymentMethodId);
273
+ return success(paymentMethod);
274
+ } catch (error) {
275
+ return handleStripeError(error);
276
+ }
277
+ }
278
+
279
+ // src/server/customers/index.ts
280
+ async function createCustomer(input) {
281
+ try {
282
+ const stripe = getStripe();
283
+ const customer = await stripe.customers.create({
284
+ email: input.email,
285
+ name: input.name,
286
+ phone: input.phone,
287
+ description: input.description,
288
+ metadata: input.metadata,
289
+ payment_method: input.paymentMethodId,
290
+ invoice_settings: input.paymentMethodId ? { default_payment_method: input.paymentMethodId } : void 0,
291
+ address: input.address ? {
292
+ line1: input.address.line1,
293
+ line2: input.address.line2,
294
+ city: input.address.city,
295
+ state: input.address.state,
296
+ postal_code: input.address.postalCode,
297
+ country: input.address.country
298
+ } : void 0
299
+ });
300
+ return success(customer);
301
+ } catch (error) {
302
+ return handleStripeError(error);
303
+ }
304
+ }
305
+ async function retrieveCustomer(customerId) {
306
+ try {
307
+ const stripe = getStripe();
308
+ const customer = await stripe.customers.retrieve(customerId, {
309
+ expand: ["subscriptions", "sources"]
310
+ });
311
+ if (customer.deleted) {
312
+ return {
313
+ data: null,
314
+ error: { message: "Customer has been deleted", type: "invalid_request_error" }
315
+ };
316
+ }
317
+ return success(customer);
318
+ } catch (error) {
319
+ return handleStripeError(error);
320
+ }
321
+ }
322
+ async function updateCustomer(input) {
323
+ try {
324
+ const stripe = getStripe();
325
+ const customer = await stripe.customers.update(input.customerId, {
326
+ email: input.email,
327
+ name: input.name,
328
+ phone: input.phone,
329
+ description: input.description,
330
+ metadata: input.metadata,
331
+ invoice_settings: input.defaultPaymentMethodId ? { default_payment_method: input.defaultPaymentMethodId } : void 0,
332
+ address: input.address ? {
333
+ line1: input.address.line1,
334
+ line2: input.address.line2,
335
+ city: input.address.city,
336
+ state: input.address.state,
337
+ postal_code: input.address.postalCode,
338
+ country: input.address.country
339
+ } : void 0
340
+ });
341
+ return success(customer);
342
+ } catch (error) {
343
+ return handleStripeError(error);
344
+ }
345
+ }
346
+ async function deleteCustomer(customerId) {
347
+ try {
348
+ const stripe = getStripe();
349
+ const deleted = await stripe.customers.del(customerId);
350
+ return success(deleted);
351
+ } catch (error) {
352
+ return handleStripeError(error);
353
+ }
354
+ }
355
+ async function listCustomers(input) {
356
+ try {
357
+ const stripe = getStripe();
358
+ const customers = await stripe.customers.list({
359
+ limit: input?.limit ?? 10,
360
+ starting_after: input?.startingAfter,
361
+ ending_before: input?.endingBefore,
362
+ email: input?.email
363
+ });
364
+ return success(customers);
365
+ } catch (error) {
366
+ return handleStripeError(error);
367
+ }
368
+ }
369
+ async function searchCustomers(query, limit) {
370
+ try {
371
+ const stripe = getStripe();
372
+ const customers = await stripe.customers.search({
373
+ query,
374
+ limit: limit ?? 10
375
+ });
376
+ return success(customers);
377
+ } catch (error) {
378
+ return handleStripeError(error);
379
+ }
380
+ }
381
+ async function createPortalSession(input) {
382
+ try {
383
+ const stripe = getStripe();
384
+ const session = await stripe.billingPortal.sessions.create({
385
+ customer: input.customerId,
386
+ return_url: input.returnUrl,
387
+ configuration: input.configuration
388
+ });
389
+ return success(session);
390
+ } catch (error) {
391
+ return handleStripeError(error);
392
+ }
393
+ }
394
+
395
+ // src/server/subscriptions/index.ts
396
+ async function createSubscription(input) {
397
+ try {
398
+ const stripe = getStripe();
399
+ const items = input.items ? input.items.map((item) => ({ price: item.priceId, quantity: item.quantity })) : [{ price: input.priceId, quantity: input.quantity ?? 1 }];
400
+ const subscription = await stripe.subscriptions.create({
401
+ customer: input.customerId,
402
+ items,
403
+ metadata: input.metadata,
404
+ trial_period_days: input.trialPeriodDays,
405
+ coupon: input.couponId,
406
+ promotion_code: input.promotionCodeId,
407
+ payment_behavior: input.paymentBehavior ?? "default_incomplete",
408
+ cancel_at_period_end: input.cancelAtPeriodEnd,
409
+ billing_cycle_anchor: input.billingCycleAnchor,
410
+ proration_behavior: input.prorationBehavior,
411
+ expand: ["latest_invoice.payment_intent"]
412
+ });
413
+ return success(subscription);
414
+ } catch (error) {
415
+ return handleStripeError(error);
416
+ }
417
+ }
418
+ async function retrieveSubscription(subscriptionId) {
419
+ try {
420
+ const stripe = getStripe();
421
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
422
+ expand: ["latest_invoice.payment_intent", "default_payment_method"]
423
+ });
424
+ return success(subscription);
425
+ } catch (error) {
426
+ return handleStripeError(error);
427
+ }
428
+ }
429
+ async function updateSubscription(input) {
430
+ try {
431
+ const stripe = getStripe();
432
+ const params = {
433
+ metadata: input.metadata,
434
+ cancel_at_period_end: input.cancelAtPeriodEnd,
435
+ proration_behavior: input.prorationBehavior,
436
+ coupon: input.couponId
437
+ };
438
+ if (input.items) {
439
+ params.items = input.items.map((item) => ({
440
+ id: item.id,
441
+ price: item.priceId,
442
+ quantity: item.quantity
443
+ }));
444
+ }
445
+ const subscription = await stripe.subscriptions.update(input.subscriptionId, params);
446
+ return success(subscription);
447
+ } catch (error) {
448
+ return handleStripeError(error);
449
+ }
450
+ }
451
+ async function cancelSubscription(input) {
452
+ try {
453
+ const stripe = getStripe();
454
+ if (input.cancelAtPeriodEnd) {
455
+ const subscription2 = await stripe.subscriptions.update(input.subscriptionId, {
456
+ cancel_at_period_end: true,
457
+ cancellation_details: input.cancellationDetails ? {
458
+ comment: input.cancellationDetails.comment,
459
+ feedback: input.cancellationDetails.feedback
460
+ } : void 0
461
+ });
462
+ return success(subscription2);
463
+ }
464
+ const subscription = await stripe.subscriptions.cancel(input.subscriptionId, {
465
+ cancellation_details: input.cancellationDetails ? {
466
+ comment: input.cancellationDetails.comment,
467
+ feedback: input.cancellationDetails.feedback
468
+ } : void 0
469
+ });
470
+ return success(subscription);
471
+ } catch (error) {
472
+ return handleStripeError(error);
473
+ }
474
+ }
475
+ async function resumeSubscription(subscriptionId) {
476
+ try {
477
+ const stripe = getStripe();
478
+ const subscription = await stripe.subscriptions.update(subscriptionId, {
479
+ cancel_at_period_end: false
480
+ });
481
+ return success(subscription);
482
+ } catch (error) {
483
+ return handleStripeError(error);
484
+ }
485
+ }
486
+ async function listSubscriptions(input) {
487
+ try {
488
+ const stripe = getStripe();
489
+ const subscriptions = await stripe.subscriptions.list({
490
+ limit: input?.limit ?? 10,
491
+ starting_after: input?.startingAfter,
492
+ ending_before: input?.endingBefore,
493
+ customer: input?.customerId,
494
+ status: input?.status
495
+ });
496
+ return success(subscriptions);
497
+ } catch (error) {
498
+ return handleStripeError(error);
499
+ }
500
+ }
501
+
502
+ // src/server/products/index.ts
503
+ async function createProduct(input) {
504
+ try {
505
+ const stripe = getStripe();
506
+ const product = await stripe.products.create({
507
+ name: input.name,
508
+ description: input.description,
509
+ images: input.images,
510
+ metadata: input.metadata,
511
+ active: input.active,
512
+ default_price_data: input.defaultPriceData ? {
513
+ unit_amount: input.defaultPriceData.unitAmount,
514
+ currency: input.defaultPriceData.currency,
515
+ recurring: input.defaultPriceData.recurring ? {
516
+ interval: input.defaultPriceData.recurring.interval,
517
+ interval_count: input.defaultPriceData.recurring.intervalCount
518
+ } : void 0
519
+ } : void 0
520
+ });
521
+ return success(product);
522
+ } catch (error) {
523
+ return handleStripeError(error);
524
+ }
525
+ }
526
+ async function retrieveProduct(productId) {
527
+ try {
528
+ const stripe = getStripe();
529
+ const product = await stripe.products.retrieve(productId);
530
+ return success(product);
531
+ } catch (error) {
532
+ return handleStripeError(error);
533
+ }
534
+ }
535
+ async function updateProduct(input) {
536
+ try {
537
+ const stripe = getStripe();
538
+ const product = await stripe.products.update(input.productId, {
539
+ name: input.name,
540
+ description: input.description,
541
+ images: input.images,
542
+ metadata: input.metadata,
543
+ active: input.active
544
+ });
545
+ return success(product);
546
+ } catch (error) {
547
+ return handleStripeError(error);
548
+ }
549
+ }
550
+ async function archiveProduct(productId) {
551
+ try {
552
+ const stripe = getStripe();
553
+ const product = await stripe.products.update(productId, { active: false });
554
+ return success(product);
555
+ } catch (error) {
556
+ return handleStripeError(error);
557
+ }
558
+ }
559
+ async function listProducts(input) {
560
+ try {
561
+ const stripe = getStripe();
562
+ const products = await stripe.products.list({
563
+ limit: input?.limit ?? 10,
564
+ starting_after: input?.startingAfter,
565
+ ending_before: input?.endingBefore,
566
+ active: input?.active
567
+ });
568
+ return success(products);
569
+ } catch (error) {
570
+ return handleStripeError(error);
571
+ }
572
+ }
573
+ async function createPrice(input) {
574
+ try {
575
+ const stripe = getStripe();
576
+ const params = {
577
+ product: input.productId,
578
+ currency: input.currency,
579
+ metadata: input.metadata,
580
+ active: input.active,
581
+ nickname: input.nickname,
582
+ lookup_key: input.lookupKey,
583
+ billing_scheme: input.billingScheme,
584
+ recurring: input.recurring ? {
585
+ interval: input.recurring.interval,
586
+ interval_count: input.recurring.intervalCount
587
+ } : void 0
588
+ };
589
+ if (input.billingScheme === "tiered" && input.tiers) {
590
+ if (!input.tiersMode) {
591
+ throw new Error('tiersMode is required when billingScheme is "tiered"');
592
+ }
593
+ params.tiers = input.tiers.map((tier) => ({
594
+ up_to: tier.upTo,
595
+ unit_amount: tier.unitAmount,
596
+ flat_amount: tier.flatAmount
597
+ }));
598
+ params.tiers_mode = input.tiersMode;
599
+ } else {
600
+ params.unit_amount = input.unitAmount;
601
+ }
602
+ const price = await stripe.prices.create(params);
603
+ return success(price);
604
+ } catch (error) {
605
+ return handleStripeError(error);
606
+ }
607
+ }
608
+ async function retrievePrice(priceId) {
609
+ try {
610
+ const stripe = getStripe();
611
+ const price = await stripe.prices.retrieve(priceId);
612
+ return success(price);
613
+ } catch (error) {
614
+ return handleStripeError(error);
615
+ }
616
+ }
617
+ async function listPrices(input) {
618
+ try {
619
+ const stripe = getStripe();
620
+ const prices = await stripe.prices.list({
621
+ limit: input?.limit ?? 10,
622
+ starting_after: input?.startingAfter,
623
+ ending_before: input?.endingBefore,
624
+ product: input?.productId,
625
+ active: input?.active,
626
+ type: input?.type
627
+ });
628
+ return success(prices);
629
+ } catch (error) {
630
+ return handleStripeError(error);
631
+ }
632
+ }
633
+ async function archivePrice(priceId) {
634
+ try {
635
+ const stripe = getStripe();
636
+ const price = await stripe.prices.update(priceId, { active: false });
637
+ return success(price);
638
+ } catch (error) {
639
+ return handleStripeError(error);
640
+ }
641
+ }
642
+
643
+ // src/server/invoices/index.ts
644
+ async function createInvoice(input) {
645
+ try {
646
+ const stripe = getStripe();
647
+ const invoice = await stripe.invoices.create({
648
+ customer: input.customerId,
649
+ collection_method: input.collectionMethod ?? "charge_automatically",
650
+ days_until_due: input.daysUntilDue,
651
+ metadata: input.metadata,
652
+ description: input.description,
653
+ auto_advance: input.autoAdvance
654
+ });
655
+ return success(invoice);
656
+ } catch (error) {
657
+ return handleStripeError(error);
658
+ }
659
+ }
660
+ async function retrieveInvoice(invoiceId) {
661
+ try {
662
+ const stripe = getStripe();
663
+ const invoice = await stripe.invoices.retrieve(invoiceId);
664
+ return success(invoice);
665
+ } catch (error) {
666
+ return handleStripeError(error);
667
+ }
668
+ }
669
+ async function finalizeInvoice(invoiceId) {
670
+ try {
671
+ const stripe = getStripe();
672
+ const invoice = await stripe.invoices.finalizeInvoice(invoiceId);
673
+ return success(invoice);
674
+ } catch (error) {
675
+ return handleStripeError(error);
676
+ }
677
+ }
678
+ async function sendInvoice(invoiceId) {
679
+ try {
680
+ const stripe = getStripe();
681
+ const invoice = await stripe.invoices.sendInvoice(invoiceId);
682
+ return success(invoice);
683
+ } catch (error) {
684
+ return handleStripeError(error);
685
+ }
686
+ }
687
+ async function payInvoice(invoiceId) {
688
+ try {
689
+ const stripe = getStripe();
690
+ const invoice = await stripe.invoices.pay(invoiceId);
691
+ return success(invoice);
692
+ } catch (error) {
693
+ return handleStripeError(error);
694
+ }
695
+ }
696
+ async function voidInvoice(invoiceId) {
697
+ try {
698
+ const stripe = getStripe();
699
+ const invoice = await stripe.invoices.voidInvoice(invoiceId);
700
+ return success(invoice);
701
+ } catch (error) {
702
+ return handleStripeError(error);
703
+ }
704
+ }
705
+ async function listInvoices(input) {
706
+ try {
707
+ const stripe = getStripe();
708
+ const invoices = await stripe.invoices.list({
709
+ limit: input?.limit ?? 10,
710
+ starting_after: input?.startingAfter,
711
+ ending_before: input?.endingBefore,
712
+ customer: input?.customerId,
713
+ status: input?.status
714
+ });
715
+ return success(invoices);
716
+ } catch (error) {
717
+ return handleStripeError(error);
718
+ }
719
+ }
720
+ async function getUpcomingInvoice(customerId, subscriptionId) {
721
+ try {
722
+ const stripe = getStripe();
723
+ const invoice = await stripe.invoices.retrieveUpcoming({
724
+ customer: customerId,
725
+ subscription: subscriptionId
726
+ });
727
+ return success(invoice);
728
+ } catch (error) {
729
+ return handleStripeError(error);
730
+ }
731
+ }
732
+ async function createInvoiceItem(input) {
733
+ try {
734
+ const stripe = getStripe();
735
+ const invoiceItem = await stripe.invoiceItems.create({
736
+ customer: input.customerId,
737
+ invoice: input.invoiceId,
738
+ price: input.priceId,
739
+ amount: input.amount,
740
+ currency: input.currency,
741
+ description: input.description,
742
+ quantity: input.quantity,
743
+ metadata: input.metadata
744
+ });
745
+ return success(invoiceItem);
746
+ } catch (error) {
747
+ return handleStripeError(error);
748
+ }
749
+ }
750
+
751
+ // src/server/refunds/index.ts
752
+ async function createRefund(input) {
753
+ try {
754
+ const stripe = getStripe();
755
+ const refund = await stripe.refunds.create({
756
+ payment_intent: input.paymentIntentId,
757
+ charge: input.chargeId,
758
+ amount: input.amount,
759
+ reason: input.reason,
760
+ metadata: input.metadata
761
+ });
762
+ return success(refund);
763
+ } catch (error) {
764
+ return handleStripeError(error);
765
+ }
766
+ }
767
+ async function retrieveRefund(refundId) {
768
+ try {
769
+ const stripe = getStripe();
770
+ const refund = await stripe.refunds.retrieve(refundId);
771
+ return success(refund);
772
+ } catch (error) {
773
+ return handleStripeError(error);
774
+ }
775
+ }
776
+ async function listRefunds(input) {
777
+ try {
778
+ const stripe = getStripe();
779
+ const refunds = await stripe.refunds.list({
780
+ limit: input?.limit ?? 10,
781
+ starting_after: input?.startingAfter,
782
+ ending_before: input?.endingBefore,
783
+ payment_intent: input?.paymentIntentId,
784
+ charge: input?.chargeId
785
+ });
786
+ return success(refunds);
787
+ } catch (error) {
788
+ return handleStripeError(error);
789
+ }
790
+ }
791
+ async function retrieveDispute(disputeId) {
792
+ try {
793
+ const stripe = getStripe();
794
+ const dispute = await stripe.disputes.retrieve(disputeId);
795
+ return success(dispute);
796
+ } catch (error) {
797
+ return handleStripeError(error);
798
+ }
799
+ }
800
+ async function updateDispute(input) {
801
+ try {
802
+ const stripe = getStripe();
803
+ const dispute = await stripe.disputes.update(input.disputeId, {
804
+ evidence: input.evidence ? {
805
+ customer_name: input.evidence.customerName,
806
+ customer_email_address: input.evidence.customerEmailAddress,
807
+ customer_communication: input.evidence.customerCommunication,
808
+ product_description: input.evidence.productDescription,
809
+ shipping_documentation: input.evidence.shippingDocumentation,
810
+ service_documentation: input.evidence.serviceDocumentation,
811
+ uncategorized_text: input.evidence.uncategorizedText
812
+ } : void 0,
813
+ metadata: input.metadata,
814
+ submit: input.submit
815
+ });
816
+ return success(dispute);
817
+ } catch (error) {
818
+ return handleStripeError(error);
819
+ }
820
+ }
821
+ async function closeDispute(disputeId) {
822
+ try {
823
+ const stripe = getStripe();
824
+ const dispute = await stripe.disputes.close(disputeId);
825
+ return success(dispute);
826
+ } catch (error) {
827
+ return handleStripeError(error);
828
+ }
829
+ }
830
+ async function listDisputes(input) {
831
+ try {
832
+ const stripe = getStripe();
833
+ const disputes = await stripe.disputes.list({
834
+ limit: input?.limit ?? 10,
835
+ starting_after: input?.startingAfter,
836
+ ending_before: input?.endingBefore
837
+ });
838
+ return success(disputes);
839
+ } catch (error) {
840
+ return handleStripeError(error);
841
+ }
842
+ }
843
+
844
+ // src/server/connect/index.ts
845
+ async function createConnectAccount(input) {
846
+ try {
847
+ const stripe = getStripe();
848
+ const account = await stripe.accounts.create({
849
+ type: input.type,
850
+ country: input.country,
851
+ email: input.email,
852
+ capabilities: input.capabilities,
853
+ business_type: input.businessType,
854
+ metadata: input.metadata
855
+ });
856
+ return success(account);
857
+ } catch (error) {
858
+ return handleStripeError(error);
859
+ }
860
+ }
861
+ async function retrieveConnectAccount(accountId) {
862
+ try {
863
+ const stripe = getStripe();
864
+ const account = await stripe.accounts.retrieve(accountId);
865
+ return success(account);
866
+ } catch (error) {
867
+ return handleStripeError(error);
868
+ }
869
+ }
870
+ async function deleteConnectAccount(accountId) {
871
+ try {
872
+ const stripe = getStripe();
873
+ const deleted = await stripe.accounts.del(accountId);
874
+ return success(deleted);
875
+ } catch (error) {
876
+ return handleStripeError(error);
877
+ }
878
+ }
879
+ async function listConnectAccounts(input) {
880
+ try {
881
+ const stripe = getStripe();
882
+ const accounts = await stripe.accounts.list({
883
+ limit: input?.limit ?? 10,
884
+ starting_after: input?.startingAfter,
885
+ ending_before: input?.endingBefore
886
+ });
887
+ return success(accounts);
888
+ } catch (error) {
889
+ return handleStripeError(error);
890
+ }
891
+ }
892
+ async function createAccountLink(input) {
893
+ try {
894
+ const stripe = getStripe();
895
+ const accountLink = await stripe.accountLinks.create({
896
+ account: input.accountId,
897
+ refresh_url: input.refreshUrl,
898
+ return_url: input.returnUrl,
899
+ type: input.type
900
+ });
901
+ return success(accountLink);
902
+ } catch (error) {
903
+ return handleStripeError(error);
904
+ }
905
+ }
906
+ async function createTransfer(input) {
907
+ try {
908
+ const stripe = getStripe();
909
+ const transfer = await stripe.transfers.create({
910
+ amount: input.amount,
911
+ currency: input.currency,
912
+ destination: input.destinationAccountId,
913
+ description: input.description,
914
+ metadata: input.metadata,
915
+ source_transaction: input.sourceTransaction
916
+ });
917
+ return success(transfer);
918
+ } catch (error) {
919
+ return handleStripeError(error);
920
+ }
921
+ }
922
+ async function listTransfers(input) {
923
+ try {
924
+ const stripe = getStripe();
925
+ const transfers = await stripe.transfers.list({
926
+ limit: input?.limit ?? 10,
927
+ starting_after: input?.startingAfter,
928
+ ending_before: input?.endingBefore,
929
+ destination: input?.destinationAccountId
930
+ });
931
+ return success(transfers);
932
+ } catch (error) {
933
+ return handleStripeError(error);
934
+ }
935
+ }
936
+ async function createPayout(amount, currency, metadata) {
937
+ try {
938
+ const stripe = getStripe();
939
+ const payout = await stripe.payouts.create({
940
+ amount,
941
+ currency,
942
+ metadata
943
+ });
944
+ return success(payout);
945
+ } catch (error) {
946
+ return handleStripeError(error);
947
+ }
948
+ }
949
+ async function listPayouts(input) {
950
+ try {
951
+ const stripe = getStripe();
952
+ const payouts = await stripe.payouts.list({
953
+ limit: input?.limit ?? 10,
954
+ starting_after: input?.startingAfter,
955
+ ending_before: input?.endingBefore,
956
+ status: input?.status
957
+ });
958
+ return success(payouts);
959
+ } catch (error) {
960
+ return handleStripeError(error);
961
+ }
962
+ }
963
+ async function getBalance() {
964
+ try {
965
+ const stripe = getStripe();
966
+ const balance = await stripe.balance.retrieve();
967
+ return success(balance);
968
+ } catch (error) {
969
+ return handleStripeError(error);
970
+ }
971
+ }
972
+ async function listBalanceTransactions(input) {
973
+ try {
974
+ const stripe = getStripe();
975
+ const transactions = await stripe.balanceTransactions.list({
976
+ limit: input?.limit ?? 10,
977
+ starting_after: input?.startingAfter,
978
+ ending_before: input?.endingBefore,
979
+ type: input?.type
980
+ });
981
+ return success(transactions);
982
+ } catch (error) {
983
+ return handleStripeError(error);
984
+ }
985
+ }
986
+
987
+ // src/server/coupons/index.ts
988
+ async function createCoupon(input) {
989
+ try {
990
+ const stripe = getStripe();
991
+ const coupon = await stripe.coupons.create({
992
+ percent_off: input.percentOff,
993
+ amount_off: input.amountOff,
994
+ currency: input.currency,
995
+ duration: input.duration,
996
+ duration_in_months: input.durationInMonths,
997
+ max_redemptions: input.maxRedemptions,
998
+ redeem_by: input.redeemBy,
999
+ name: input.name,
1000
+ metadata: input.metadata
1001
+ });
1002
+ return success(coupon);
1003
+ } catch (error) {
1004
+ return handleStripeError(error);
1005
+ }
1006
+ }
1007
+ async function retrieveCoupon(couponId) {
1008
+ try {
1009
+ const stripe = getStripe();
1010
+ const coupon = await stripe.coupons.retrieve(couponId);
1011
+ return success(coupon);
1012
+ } catch (error) {
1013
+ return handleStripeError(error);
1014
+ }
1015
+ }
1016
+ async function deleteCoupon(couponId) {
1017
+ try {
1018
+ const stripe = getStripe();
1019
+ const deleted = await stripe.coupons.del(couponId);
1020
+ return success(deleted);
1021
+ } catch (error) {
1022
+ return handleStripeError(error);
1023
+ }
1024
+ }
1025
+ async function listCoupons(input) {
1026
+ try {
1027
+ const stripe = getStripe();
1028
+ const coupons = await stripe.coupons.list({
1029
+ limit: input?.limit ?? 10,
1030
+ starting_after: input?.startingAfter,
1031
+ ending_before: input?.endingBefore
1032
+ });
1033
+ return success(coupons);
1034
+ } catch (error) {
1035
+ return handleStripeError(error);
1036
+ }
1037
+ }
1038
+ async function createPromotionCode(input) {
1039
+ try {
1040
+ const stripe = getStripe();
1041
+ const promotionCode = await stripe.promotionCodes.create({
1042
+ coupon: input.couponId,
1043
+ code: input.code,
1044
+ active: input.active,
1045
+ max_redemptions: input.maxRedemptions,
1046
+ expires_at: input.expiresAt,
1047
+ metadata: input.metadata,
1048
+ restrictions: input.restrictions ? {
1049
+ first_time_transaction: input.restrictions.firstTimeTransaction,
1050
+ minimum_amount: input.restrictions.minimumAmount,
1051
+ minimum_amount_currency: input.restrictions.minimumAmountCurrency
1052
+ } : void 0
1053
+ });
1054
+ return success(promotionCode);
1055
+ } catch (error) {
1056
+ return handleStripeError(error);
1057
+ }
1058
+ }
1059
+ async function retrievePromotionCode(promotionCodeId) {
1060
+ try {
1061
+ const stripe = getStripe();
1062
+ const promotionCode = await stripe.promotionCodes.retrieve(promotionCodeId);
1063
+ return success(promotionCode);
1064
+ } catch (error) {
1065
+ return handleStripeError(error);
1066
+ }
1067
+ }
1068
+ async function listPromotionCodes(input) {
1069
+ try {
1070
+ const stripe = getStripe();
1071
+ const promotionCodes = await stripe.promotionCodes.list({
1072
+ limit: input?.limit ?? 10,
1073
+ starting_after: input?.startingAfter,
1074
+ ending_before: input?.endingBefore,
1075
+ coupon: input?.couponId,
1076
+ active: input?.active,
1077
+ code: input?.code
1078
+ });
1079
+ return success(promotionCodes);
1080
+ } catch (error) {
1081
+ return handleStripeError(error);
1082
+ }
1083
+ }
1084
+
1085
+ // src/server/webhooks/index.ts
1086
+ var MAX_BODY_SIZE = 1024 * 1024;
1087
+ function createWebhookHandler(config) {
1088
+ const webhookSecret = config.secret ?? getConfig().webhookSecret;
1089
+ if (!webhookSecret) {
1090
+ throw new Error(
1091
+ "[@stripe-sdk/core] Webhook secret is required. Pass it via config.secret or initStripe({ webhookSecret })."
1092
+ );
1093
+ }
1094
+ return async function handleWebhook(body, signature) {
1095
+ const stripe = getStripe();
1096
+ let event;
1097
+ try {
1098
+ event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
1099
+ } catch (err) {
1100
+ const verificationError = err instanceof Error ? err : new Error("Webhook signature verification failed");
1101
+ if (config.onError) {
1102
+ await config.onError(verificationError);
1103
+ }
1104
+ throw verificationError;
1105
+ }
1106
+ const handler = config.handlers[event.type];
1107
+ if (handler) {
1108
+ try {
1109
+ await handler(event);
1110
+ } catch (error) {
1111
+ if (config.onError) {
1112
+ await config.onError(error instanceof Error ? error : new Error(String(error)), event);
1113
+ } else {
1114
+ throw error;
1115
+ }
1116
+ }
1117
+ } else if (config.onUnhandledEvent) {
1118
+ await config.onUnhandledEvent(event);
1119
+ }
1120
+ return { received: true, type: event.type };
1121
+ };
1122
+ }
1123
+ function createNextWebhookHandler(config) {
1124
+ const handler = createWebhookHandler(config);
1125
+ return async function POST(request) {
1126
+ try {
1127
+ const contentLength = request.headers.get("content-length");
1128
+ if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
1129
+ return new Response(JSON.stringify({ error: "Webhook body too large" }), {
1130
+ status: 413,
1131
+ headers: { "Content-Type": "application/json" }
1132
+ });
1133
+ }
1134
+ const body = await request.text();
1135
+ const signature = request.headers.get("stripe-signature");
1136
+ if (!signature) {
1137
+ return new Response(JSON.stringify({ error: "Missing stripe-signature header" }), {
1138
+ status: 400,
1139
+ headers: { "Content-Type": "application/json" }
1140
+ });
1141
+ }
1142
+ const result = await handler(body, signature);
1143
+ return new Response(JSON.stringify(result), {
1144
+ status: 200,
1145
+ headers: { "Content-Type": "application/json" }
1146
+ });
1147
+ } catch (error) {
1148
+ const message = error instanceof Error ? error.message : "Webhook handler failed";
1149
+ return new Response(JSON.stringify({ error: message }), {
1150
+ status: 400,
1151
+ headers: { "Content-Type": "application/json" }
1152
+ });
1153
+ }
1154
+ };
1155
+ }
1156
+ function createPagesWebhookHandler(webhookConfig) {
1157
+ const handler = createWebhookHandler(webhookConfig);
1158
+ return async function webhookRoute(req, res) {
1159
+ if (req.method !== "POST") {
1160
+ res.status(405).end();
1161
+ return;
1162
+ }
1163
+ try {
1164
+ const body = await getRawBody(req);
1165
+ const signature = req.headers["stripe-signature"];
1166
+ if (!signature) {
1167
+ res.status(400).json({ error: "Missing stripe-signature header" });
1168
+ return;
1169
+ }
1170
+ const result = await handler(body, signature);
1171
+ res.status(200).json(result);
1172
+ } catch (error) {
1173
+ const message = error instanceof Error ? error.message : "Webhook handler failed";
1174
+ res.status(400).json({ error: message });
1175
+ }
1176
+ };
1177
+ }
1178
+ function getRawBody(req) {
1179
+ return new Promise((resolve, reject) => {
1180
+ if (typeof req.body === "string") {
1181
+ if (req.body.length > MAX_BODY_SIZE) {
1182
+ reject(new Error("Webhook body too large"));
1183
+ return;
1184
+ }
1185
+ resolve(req.body);
1186
+ return;
1187
+ }
1188
+ if (Buffer.isBuffer(req.body)) {
1189
+ if (req.body.length > MAX_BODY_SIZE) {
1190
+ reject(new Error("Webhook body too large"));
1191
+ return;
1192
+ }
1193
+ resolve(req.body.toString("utf8"));
1194
+ return;
1195
+ }
1196
+ if (!req.on) {
1197
+ reject(new Error("Cannot read raw body from request"));
1198
+ return;
1199
+ }
1200
+ const chunks = [];
1201
+ let totalLength = 0;
1202
+ req.on("data", (chunk) => {
1203
+ const buf = Buffer.from(chunk);
1204
+ totalLength += buf.length;
1205
+ if (totalLength > MAX_BODY_SIZE) {
1206
+ reject(new Error("Webhook body too large"));
1207
+ return;
1208
+ }
1209
+ chunks.push(buf);
1210
+ });
1211
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
1212
+ req.on("error", reject);
1213
+ });
1214
+ }
1215
+ var StripeContext = react.createContext(null);
1216
+ function useStripeConfig() {
1217
+ const context = react.useContext(StripeContext);
1218
+ if (!context) {
1219
+ throw new Error("useStripeConfig must be used within a <StripeProvider>");
1220
+ }
1221
+ return context;
1222
+ }
1223
+ function StripeProvider({
1224
+ publishableKey,
1225
+ children,
1226
+ options,
1227
+ locale
1228
+ }) {
1229
+ const stripePromise = react.useMemo(
1230
+ () => stripeJs.loadStripe(publishableKey, locale ? { locale } : void 0),
1231
+ [publishableKey, locale]
1232
+ );
1233
+ return /* @__PURE__ */ jsxRuntime.jsx(StripeContext.Provider, { value: { publishableKey }, children: /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.Elements, { stripe: stripePromise, options, children }) });
1234
+ }
1235
+ function StripeElementsProvider({
1236
+ publishableKey,
1237
+ clientSecret,
1238
+ children,
1239
+ appearance,
1240
+ locale,
1241
+ loader = "auto"
1242
+ }) {
1243
+ const stripePromise = react.useMemo(
1244
+ () => stripeJs.loadStripe(publishableKey, locale ? { locale } : void 0),
1245
+ [publishableKey, locale]
1246
+ );
1247
+ const options = react.useMemo(
1248
+ () => ({
1249
+ clientSecret,
1250
+ appearance,
1251
+ loader
1252
+ }),
1253
+ [clientSecret, appearance, loader]
1254
+ );
1255
+ return /* @__PURE__ */ jsxRuntime.jsx(StripeContext.Provider, { value: { publishableKey }, children: /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.Elements, { stripe: stripePromise, options, children }) });
1256
+ }
1257
+ function usePayment(options) {
1258
+ const stripe = reactStripeJs.useStripe();
1259
+ const elements = reactStripeJs.useElements();
1260
+ const [state, setState] = react.useState({
1261
+ isProcessing: false,
1262
+ isSuccess: false,
1263
+ error: null,
1264
+ paymentIntentId: null
1265
+ });
1266
+ const processPayment = react.useCallback(async (overrides) => {
1267
+ if (!stripe || !elements) {
1268
+ setState((s) => ({ ...s, error: "Stripe not loaded yet" }));
1269
+ return { success: false, error: "Stripe not loaded yet" };
1270
+ }
1271
+ setState({ isProcessing: true, isSuccess: false, error: null, paymentIntentId: null });
1272
+ const { error, paymentIntent } = await stripe.confirmPayment({
1273
+ elements,
1274
+ confirmParams: {
1275
+ return_url: overrides?.returnUrl ?? options?.returnUrl ?? (typeof window !== "undefined" ? window.location.href : "")
1276
+ },
1277
+ redirect: "if_required"
1278
+ });
1279
+ if (error) {
1280
+ const message = error.message ?? "Payment failed";
1281
+ setState({ isProcessing: false, isSuccess: false, error: message, paymentIntentId: null });
1282
+ options?.onError?.(message);
1283
+ return { success: false, error: message };
1284
+ }
1285
+ if (paymentIntent?.status === "succeeded") {
1286
+ setState({ isProcessing: false, isSuccess: true, error: null, paymentIntentId: paymentIntent.id });
1287
+ options?.onSuccess?.(paymentIntent.id);
1288
+ return { success: true, paymentIntentId: paymentIntent.id };
1289
+ }
1290
+ setState({ isProcessing: false, isSuccess: false, error: null, paymentIntentId: paymentIntent?.id ?? null });
1291
+ return { success: false, status: paymentIntent?.status };
1292
+ }, [stripe, elements, options]);
1293
+ const reset = react.useCallback(() => {
1294
+ setState({ isProcessing: false, isSuccess: false, error: null, paymentIntentId: null });
1295
+ }, []);
1296
+ return {
1297
+ ...state,
1298
+ processPayment,
1299
+ reset,
1300
+ isReady: !!stripe && !!elements
1301
+ };
1302
+ }
1303
+ function useSetupIntent(options) {
1304
+ const stripe = reactStripeJs.useStripe();
1305
+ const elements = reactStripeJs.useElements();
1306
+ const [state, setState] = react.useState({
1307
+ isProcessing: false,
1308
+ isSuccess: false,
1309
+ error: null,
1310
+ setupIntentId: null,
1311
+ paymentMethodId: null
1312
+ });
1313
+ const confirmSetup = react.useCallback(async (overrides) => {
1314
+ if (!stripe || !elements) {
1315
+ setState((s) => ({ ...s, error: "Stripe not loaded yet" }));
1316
+ return { success: false, error: "Stripe not loaded yet" };
1317
+ }
1318
+ setState({ isProcessing: true, isSuccess: false, error: null, setupIntentId: null, paymentMethodId: null });
1319
+ const { error, setupIntent } = await stripe.confirmSetup({
1320
+ elements,
1321
+ confirmParams: {
1322
+ return_url: overrides?.returnUrl ?? options?.returnUrl ?? (typeof window !== "undefined" ? window.location.href : "")
1323
+ },
1324
+ redirect: "if_required"
1325
+ });
1326
+ if (error) {
1327
+ const message = error.message ?? "Setup failed";
1328
+ setState({ isProcessing: false, isSuccess: false, error: message, setupIntentId: null, paymentMethodId: null });
1329
+ options?.onError?.(message);
1330
+ return { success: false, error: message };
1331
+ }
1332
+ if (setupIntent?.status === "succeeded") {
1333
+ const pmId = typeof setupIntent.payment_method === "string" ? setupIntent.payment_method : setupIntent.payment_method?.id ?? null;
1334
+ setState({ isProcessing: false, isSuccess: true, error: null, setupIntentId: setupIntent.id, paymentMethodId: pmId });
1335
+ if (pmId) options?.onSuccess?.(setupIntent.id, pmId);
1336
+ return { success: true, setupIntentId: setupIntent.id, paymentMethodId: pmId };
1337
+ }
1338
+ setState({ isProcessing: false, isSuccess: false, error: null, setupIntentId: setupIntent?.id ?? null, paymentMethodId: null });
1339
+ return { success: false, status: setupIntent?.status };
1340
+ }, [stripe, elements, options]);
1341
+ const reset = react.useCallback(() => {
1342
+ setState({ isProcessing: false, isSuccess: false, error: null, setupIntentId: null, paymentMethodId: null });
1343
+ }, []);
1344
+ return {
1345
+ ...state,
1346
+ confirmSetup,
1347
+ reset,
1348
+ isReady: !!stripe && !!elements
1349
+ };
1350
+ }
1351
+ function useCheckout(options) {
1352
+ const [state, setState] = react.useState({
1353
+ isLoading: false,
1354
+ error: null
1355
+ });
1356
+ const redirectToCheckout = react.useCallback(async (sessionId) => {
1357
+ setState({ isLoading: true, error: null });
1358
+ try {
1359
+ const stripe = await stripeJs.loadStripe(options.publishableKey);
1360
+ if (!stripe) {
1361
+ throw new Error("Failed to load Stripe");
1362
+ }
1363
+ const { error } = await stripe.redirectToCheckout({ sessionId });
1364
+ if (error) {
1365
+ const message = error.message ?? "Redirect to checkout failed";
1366
+ setState({ isLoading: false, error: message });
1367
+ options.onError?.(message);
1368
+ return { success: false, error: message };
1369
+ }
1370
+ return { success: true };
1371
+ } catch (err) {
1372
+ const message = err instanceof Error ? err.message : "Unknown error";
1373
+ setState({ isLoading: false, error: message });
1374
+ options.onError?.(message);
1375
+ return { success: false, error: message };
1376
+ }
1377
+ }, [options]);
1378
+ const redirectToPortal = react.useCallback((portalUrl) => {
1379
+ window.location.href = portalUrl;
1380
+ }, []);
1381
+ return {
1382
+ ...state,
1383
+ redirectToCheckout,
1384
+ redirectToPortal
1385
+ };
1386
+ }
1387
+ function CheckoutForm({
1388
+ onSuccess,
1389
+ onError,
1390
+ returnUrl,
1391
+ submitLabel = "Pay now",
1392
+ showEmail = false,
1393
+ className,
1394
+ buttonClassName,
1395
+ errorClassName,
1396
+ children,
1397
+ layout = "tabs"
1398
+ }) {
1399
+ const { processPayment, isProcessing, isSuccess, error, isReady } = usePayment({
1400
+ onSuccess,
1401
+ onError,
1402
+ returnUrl
1403
+ });
1404
+ const handleSubmit = async (e) => {
1405
+ e.preventDefault();
1406
+ await processPayment();
1407
+ };
1408
+ if (isSuccess) {
1409
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: children ?? /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Payment successful!" }) });
1410
+ }
1411
+ return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleSubmit, className, children: [
1412
+ showEmail && /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.LinkAuthenticationElement, {}),
1413
+ /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.PaymentElement, { options: { layout } }),
1414
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { className: errorClassName, role: "alert", children: error }),
1415
+ /* @__PURE__ */ jsxRuntime.jsx(
1416
+ "button",
1417
+ {
1418
+ type: "submit",
1419
+ disabled: !isReady || isProcessing,
1420
+ className: buttonClassName,
1421
+ children: isProcessing ? "Processing..." : submitLabel
1422
+ }
1423
+ )
1424
+ ] });
1425
+ }
1426
+ function SetupForm({
1427
+ onSuccess,
1428
+ onError,
1429
+ returnUrl,
1430
+ submitLabel = "Save payment method",
1431
+ className,
1432
+ buttonClassName,
1433
+ errorClassName,
1434
+ successContent,
1435
+ layout = "tabs"
1436
+ }) {
1437
+ const { confirmSetup, isProcessing, isSuccess, error, isReady } = useSetupIntent({
1438
+ onSuccess,
1439
+ onError,
1440
+ returnUrl
1441
+ });
1442
+ const handleSubmit = async (e) => {
1443
+ e.preventDefault();
1444
+ await confirmSetup();
1445
+ };
1446
+ if (isSuccess) {
1447
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className, children: successContent ?? /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Payment method saved!" }) });
1448
+ }
1449
+ return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleSubmit, className, children: [
1450
+ /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.PaymentElement, { options: { layout } }),
1451
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { className: errorClassName, role: "alert", children: error }),
1452
+ /* @__PURE__ */ jsxRuntime.jsx(
1453
+ "button",
1454
+ {
1455
+ type: "submit",
1456
+ disabled: !isReady || isProcessing,
1457
+ className: buttonClassName,
1458
+ children: isProcessing ? "Saving..." : submitLabel
1459
+ }
1460
+ )
1461
+ ] });
1462
+ }
1463
+ function defaultFormatPrice(amount, currency) {
1464
+ return new Intl.NumberFormat(void 0, {
1465
+ style: "currency",
1466
+ currency,
1467
+ minimumFractionDigits: 0
1468
+ }).format(amount / 100);
1469
+ }
1470
+ function PricingTable({
1471
+ plans,
1472
+ onSelectPlan,
1473
+ isLoading,
1474
+ currentPlanId,
1475
+ buttonLabel = "Get started",
1476
+ currentPlanLabel = "Current plan",
1477
+ className,
1478
+ planClassName,
1479
+ highlightedClassName,
1480
+ buttonClassName,
1481
+ formatPrice = defaultFormatPrice,
1482
+ renderFeature
1483
+ }) {
1484
+ const defaultStyles = {
1485
+ container: {
1486
+ display: "grid",
1487
+ gridTemplateColumns: `repeat(${Math.min(plans.length, 4)}, 1fr)`,
1488
+ gap: "1.5rem",
1489
+ maxWidth: "1200px",
1490
+ margin: "0 auto"
1491
+ },
1492
+ plan: {
1493
+ border: "1px solid #e5e7eb",
1494
+ borderRadius: "0.75rem",
1495
+ padding: "2rem",
1496
+ display: "flex",
1497
+ flexDirection: "column"
1498
+ },
1499
+ highlighted: {
1500
+ border: "2px solid #6366f1",
1501
+ boxShadow: "0 4px 14px rgba(99,102,241,0.15)"
1502
+ },
1503
+ badge: {
1504
+ background: "#6366f1",
1505
+ color: "#fff",
1506
+ padding: "0.25rem 0.75rem",
1507
+ borderRadius: "9999px",
1508
+ fontSize: "0.75rem",
1509
+ fontWeight: 600,
1510
+ alignSelf: "flex-start",
1511
+ marginBottom: "0.5rem"
1512
+ },
1513
+ name: { fontSize: "1.25rem", fontWeight: 700, margin: "0 0 0.25rem" },
1514
+ description: { color: "#6b7280", fontSize: "0.875rem", margin: "0 0 1rem" },
1515
+ price: { fontSize: "2.5rem", fontWeight: 800, margin: "0" },
1516
+ interval: { color: "#6b7280", fontSize: "0.875rem", fontWeight: 400 },
1517
+ features: { listStyle: "none", padding: 0, margin: "1.5rem 0", flex: 1 },
1518
+ feature: { padding: "0.375rem 0", fontSize: "0.875rem" },
1519
+ button: {
1520
+ padding: "0.75rem 1.5rem",
1521
+ borderRadius: "0.5rem",
1522
+ border: "none",
1523
+ fontWeight: 600,
1524
+ cursor: "pointer",
1525
+ fontSize: "0.875rem",
1526
+ background: "#6366f1",
1527
+ color: "#fff",
1528
+ width: "100%"
1529
+ },
1530
+ currentButton: {
1531
+ background: "#e5e7eb",
1532
+ color: "#374151",
1533
+ cursor: "default"
1534
+ }
1535
+ };
1536
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className, style: !className ? defaultStyles.container : void 0, children: plans.map((plan) => {
1537
+ const isCurrent = plan.id === currentPlanId;
1538
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1539
+ "div",
1540
+ {
1541
+ className: plan.highlighted ? highlightedClassName : planClassName,
1542
+ style: !planClassName ? { ...defaultStyles.plan, ...plan.highlighted ? defaultStyles.highlighted : {} } : void 0,
1543
+ children: [
1544
+ plan.badge && /* @__PURE__ */ jsxRuntime.jsx("span", { style: !highlightedClassName ? defaultStyles.badge : void 0, children: plan.badge }),
1545
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { style: defaultStyles.name, children: plan.name }),
1546
+ plan.description && /* @__PURE__ */ jsxRuntime.jsx("p", { style: defaultStyles.description, children: plan.description }),
1547
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: defaultStyles.price, children: [
1548
+ formatPrice(plan.amount, plan.currency),
1549
+ plan.interval && /* @__PURE__ */ jsxRuntime.jsxs("span", { style: defaultStyles.interval, children: [
1550
+ " / ",
1551
+ plan.interval
1552
+ ] })
1553
+ ] }),
1554
+ plan.trialDays && /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { ...defaultStyles.description, marginTop: "0.5rem" }, children: [
1555
+ plan.trialDays,
1556
+ "-day free trial"
1557
+ ] }),
1558
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { style: defaultStyles.features, children: plan.features.map((feature, i) => /* @__PURE__ */ jsxRuntime.jsx("li", { style: defaultStyles.feature, children: renderFeature ? renderFeature(feature) : `\u2713 ${feature}` }, i)) }),
1559
+ /* @__PURE__ */ jsxRuntime.jsx(
1560
+ "button",
1561
+ {
1562
+ onClick: () => !isCurrent && onSelectPlan(plan),
1563
+ disabled: isLoading || isCurrent,
1564
+ className: buttonClassName,
1565
+ style: !buttonClassName ? { ...defaultStyles.button, ...isCurrent ? defaultStyles.currentButton : {} } : void 0,
1566
+ children: isCurrent ? currentPlanLabel : buttonLabel
1567
+ }
1568
+ )
1569
+ ]
1570
+ },
1571
+ plan.id
1572
+ );
1573
+ }) });
1574
+ }
1575
+ function defaultFormatPrice2(amount, currency) {
1576
+ return new Intl.NumberFormat(void 0, {
1577
+ style: "currency",
1578
+ currency,
1579
+ minimumFractionDigits: 0
1580
+ }).format(amount / 100);
1581
+ }
1582
+ var statusColors = {
1583
+ active: "#10b981",
1584
+ trialing: "#6366f1",
1585
+ past_due: "#f59e0b",
1586
+ canceled: "#ef4444",
1587
+ incomplete: "#f59e0b",
1588
+ unpaid: "#ef4444",
1589
+ paused: "#6b7280"
1590
+ };
1591
+ function SubscriptionManager({
1592
+ subscription,
1593
+ onCancel,
1594
+ onResume,
1595
+ onChangePlan,
1596
+ onManageBilling,
1597
+ className,
1598
+ formatPrice = defaultFormatPrice2,
1599
+ cancelLabel = "Cancel subscription",
1600
+ resumeLabel = "Resume subscription",
1601
+ changePlanLabel = "Change plan",
1602
+ manageBillingLabel = "Manage billing"
1603
+ }) {
1604
+ const [isLoading, setIsLoading] = react.useState(false);
1605
+ const [showConfirm, setShowConfirm] = react.useState(false);
1606
+ const endDate = new Date(subscription.currentPeriodEnd).toLocaleDateString();
1607
+ const trialEndDate = subscription.trialEnd ? new Date(subscription.trialEnd).toLocaleDateString() : null;
1608
+ const handleCancel = async () => {
1609
+ setIsLoading(true);
1610
+ try {
1611
+ await onCancel(subscription.id);
1612
+ } finally {
1613
+ setIsLoading(false);
1614
+ setShowConfirm(false);
1615
+ }
1616
+ };
1617
+ const handleResume = async () => {
1618
+ if (!onResume) return;
1619
+ setIsLoading(true);
1620
+ try {
1621
+ await onResume(subscription.id);
1622
+ } finally {
1623
+ setIsLoading(false);
1624
+ }
1625
+ };
1626
+ const styles = {
1627
+ container: { border: "1px solid #e5e7eb", borderRadius: "0.75rem", padding: "1.5rem" },
1628
+ header: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" },
1629
+ planName: { fontSize: "1.25rem", fontWeight: 700, margin: 0 },
1630
+ status: {
1631
+ padding: "0.25rem 0.75rem",
1632
+ borderRadius: "9999px",
1633
+ fontSize: "0.75rem",
1634
+ fontWeight: 600,
1635
+ color: "#fff",
1636
+ background: statusColors[subscription.status] ?? "#6b7280"
1637
+ },
1638
+ price: { fontSize: "1.5rem", fontWeight: 700, margin: "0 0 0.5rem" },
1639
+ detail: { color: "#6b7280", fontSize: "0.875rem", margin: "0.25rem 0" },
1640
+ actions: { display: "flex", gap: "0.75rem", marginTop: "1.5rem", flexWrap: "wrap" },
1641
+ button: {
1642
+ padding: "0.5rem 1rem",
1643
+ borderRadius: "0.375rem",
1644
+ border: "1px solid #d1d5db",
1645
+ background: "#fff",
1646
+ cursor: "pointer",
1647
+ fontSize: "0.875rem",
1648
+ fontWeight: 500
1649
+ },
1650
+ dangerButton: {
1651
+ padding: "0.5rem 1rem",
1652
+ borderRadius: "0.375rem",
1653
+ border: "1px solid #fca5a5",
1654
+ background: "#fef2f2",
1655
+ color: "#dc2626",
1656
+ cursor: "pointer",
1657
+ fontSize: "0.875rem",
1658
+ fontWeight: 500
1659
+ },
1660
+ confirm: {
1661
+ background: "#fef2f2",
1662
+ border: "1px solid #fca5a5",
1663
+ borderRadius: "0.5rem",
1664
+ padding: "1rem",
1665
+ marginTop: "1rem"
1666
+ }
1667
+ };
1668
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className, style: !className ? styles.container : void 0, children: [
1669
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.header, children: [
1670
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { style: styles.planName, children: subscription.planName }),
1671
+ /* @__PURE__ */ jsxRuntime.jsx("span", { style: styles.status, children: subscription.status })
1672
+ ] }),
1673
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: styles.price, children: [
1674
+ formatPrice(subscription.amount, subscription.currency),
1675
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { style: { fontSize: "0.875rem", fontWeight: 400, color: "#6b7280" }, children: [
1676
+ " ",
1677
+ "/ ",
1678
+ subscription.interval
1679
+ ] })
1680
+ ] }),
1681
+ trialEndDate && subscription.status === "trialing" && /* @__PURE__ */ jsxRuntime.jsxs("p", { style: styles.detail, children: [
1682
+ "Trial ends on ",
1683
+ trialEndDate
1684
+ ] }),
1685
+ subscription.cancelAtPeriodEnd ? /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { ...styles.detail, color: "#dc2626" }, children: [
1686
+ "Cancels on ",
1687
+ endDate
1688
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("p", { style: styles.detail, children: [
1689
+ "Renews on ",
1690
+ endDate
1691
+ ] }),
1692
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.actions, children: [
1693
+ onChangePlan && subscription.status === "active" && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => onChangePlan(subscription.id), style: styles.button, children: changePlanLabel }),
1694
+ onManageBilling && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onManageBilling, style: styles.button, children: manageBillingLabel }),
1695
+ subscription.cancelAtPeriodEnd && onResume ? /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: handleResume, disabled: isLoading, style: styles.button, children: isLoading ? "Loading..." : resumeLabel }) : subscription.status === "active" && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => setShowConfirm(true), style: styles.dangerButton, children: cancelLabel })
1696
+ ] }),
1697
+ showConfirm && /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.confirm, children: [
1698
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: "0 0 0.75rem", fontWeight: 500 }, children: "Are you sure you want to cancel?" }),
1699
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { ...styles.detail, marginBottom: "0.75rem" }, children: [
1700
+ "You will still have access until ",
1701
+ endDate,
1702
+ "."
1703
+ ] }),
1704
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: "0.5rem" }, children: [
1705
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: handleCancel, disabled: isLoading, style: styles.dangerButton, children: isLoading ? "Cancelling..." : "Confirm cancellation" }),
1706
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => setShowConfirm(false), style: styles.button, children: "Keep subscription" })
1707
+ ] })
1708
+ ] })
1709
+ ] });
1710
+ }
1711
+
1712
+ exports.CheckoutForm = CheckoutForm;
1713
+ exports.PricingTable = PricingTable;
1714
+ exports.SetupForm = SetupForm;
1715
+ exports.StripeElementsProvider = StripeElementsProvider;
1716
+ exports.StripeProvider = StripeProvider;
1717
+ exports.SubscriptionManager = SubscriptionManager;
1718
+ exports.archivePrice = archivePrice;
1719
+ exports.archiveProduct = archiveProduct;
1720
+ exports.attachPaymentMethod = attachPaymentMethod;
1721
+ exports.cancelPaymentIntent = cancelPaymentIntent;
1722
+ exports.cancelSubscription = cancelSubscription;
1723
+ exports.closeDispute = closeDispute;
1724
+ exports.confirmPaymentIntent = confirmPaymentIntent;
1725
+ exports.createAccountLink = createAccountLink;
1726
+ exports.createCheckoutSession = createCheckoutSession;
1727
+ exports.createConnectAccount = createConnectAccount;
1728
+ exports.createCoupon = createCoupon;
1729
+ exports.createCustomer = createCustomer;
1730
+ exports.createInvoice = createInvoice;
1731
+ exports.createInvoiceItem = createInvoiceItem;
1732
+ exports.createNextWebhookHandler = createNextWebhookHandler;
1733
+ exports.createPagesWebhookHandler = createPagesWebhookHandler;
1734
+ exports.createPaymentIntent = createPaymentIntent;
1735
+ exports.createPaymentLink = createPaymentLink;
1736
+ exports.createPayout = createPayout;
1737
+ exports.createPortalSession = createPortalSession;
1738
+ exports.createPrice = createPrice;
1739
+ exports.createProduct = createProduct;
1740
+ exports.createPromotionCode = createPromotionCode;
1741
+ exports.createRefund = createRefund;
1742
+ exports.createSetupIntent = createSetupIntent;
1743
+ exports.createSubscription = createSubscription;
1744
+ exports.createTransfer = createTransfer;
1745
+ exports.createWebhookHandler = createWebhookHandler;
1746
+ exports.deleteConnectAccount = deleteConnectAccount;
1747
+ exports.deleteCoupon = deleteCoupon;
1748
+ exports.deleteCustomer = deleteCustomer;
1749
+ exports.detachPaymentMethod = detachPaymentMethod;
1750
+ exports.finalizeInvoice = finalizeInvoice;
1751
+ exports.getBalance = getBalance;
1752
+ exports.getConfig = getConfig;
1753
+ exports.getStripe = getStripe;
1754
+ exports.getUpcomingInvoice = getUpcomingInvoice;
1755
+ exports.initStripe = initStripe;
1756
+ exports.listBalanceTransactions = listBalanceTransactions;
1757
+ exports.listCheckoutSessions = listCheckoutSessions;
1758
+ exports.listConnectAccounts = listConnectAccounts;
1759
+ exports.listCoupons = listCoupons;
1760
+ exports.listCustomers = listCustomers;
1761
+ exports.listDisputes = listDisputes;
1762
+ exports.listInvoices = listInvoices;
1763
+ exports.listPaymentIntents = listPaymentIntents;
1764
+ exports.listPaymentMethods = listPaymentMethods;
1765
+ exports.listPayouts = listPayouts;
1766
+ exports.listPrices = listPrices;
1767
+ exports.listProducts = listProducts;
1768
+ exports.listPromotionCodes = listPromotionCodes;
1769
+ exports.listRefunds = listRefunds;
1770
+ exports.listSubscriptions = listSubscriptions;
1771
+ exports.listTransfers = listTransfers;
1772
+ exports.payInvoice = payInvoice;
1773
+ exports.resumeSubscription = resumeSubscription;
1774
+ exports.retrieveCheckoutSession = retrieveCheckoutSession;
1775
+ exports.retrieveConnectAccount = retrieveConnectAccount;
1776
+ exports.retrieveCoupon = retrieveCoupon;
1777
+ exports.retrieveCustomer = retrieveCustomer;
1778
+ exports.retrieveDispute = retrieveDispute;
1779
+ exports.retrieveInvoice = retrieveInvoice;
1780
+ exports.retrievePaymentIntent = retrievePaymentIntent;
1781
+ exports.retrievePaymentLink = retrievePaymentLink;
1782
+ exports.retrievePrice = retrievePrice;
1783
+ exports.retrieveProduct = retrieveProduct;
1784
+ exports.retrievePromotionCode = retrievePromotionCode;
1785
+ exports.retrieveRefund = retrieveRefund;
1786
+ exports.retrieveSetupIntent = retrieveSetupIntent;
1787
+ exports.retrieveSubscription = retrieveSubscription;
1788
+ exports.searchCustomers = searchCustomers;
1789
+ exports.sendInvoice = sendInvoice;
1790
+ exports.updateCustomer = updateCustomer;
1791
+ exports.updateDispute = updateDispute;
1792
+ exports.updateProduct = updateProduct;
1793
+ exports.updateSubscription = updateSubscription;
1794
+ exports.useCheckout = useCheckout;
1795
+ exports.usePayment = usePayment;
1796
+ exports.useSetupIntent = useSetupIntent;
1797
+ exports.useStripeConfig = useStripeConfig;
1798
+ exports.voidInvoice = voidInvoice;
1799
+ //# sourceMappingURL=index.js.map
1800
+ //# sourceMappingURL=index.js.map