@solvapay/react 1.0.0-preview.2 → 1.0.0-preview.20

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 CHANGED
@@ -1,194 +1,668 @@
1
+ import {
2
+ defaultAuthAdapter
3
+ } from "./chunk-OUSEQRCT.js";
4
+
1
5
  // src/SolvaPayProvider.tsx
2
- import { useState, useEffect } from "react";
3
- import { Elements } from "@stripe/react-stripe-js";
4
- import { loadStripe } from "@stripe/stripe-js";
5
- import { jsx, jsxs } from "react/jsx-runtime";
6
+ import { createContext, useState, useEffect, useCallback, useMemo, useRef } from "react";
7
+
8
+ // src/utils/purchases.ts
9
+ function filterPurchases(purchases) {
10
+ return purchases.filter((purchase) => purchase.status === "active");
11
+ }
12
+ function getActivePurchases(purchases) {
13
+ return purchases.filter((purchase) => purchase.status === "active");
14
+ }
15
+ function getCancelledPurchasesWithEndDate(purchases) {
16
+ const now = /* @__PURE__ */ new Date();
17
+ return purchases.filter((purchase) => {
18
+ return purchase.status === "active" && purchase.cancelledAt && purchase.endDate && new Date(purchase.endDate) > now;
19
+ });
20
+ }
21
+ function getMostRecentPurchase(purchases) {
22
+ if (purchases.length === 0) return null;
23
+ return purchases.reduce((latest, current) => {
24
+ return new Date(current.startDate) > new Date(latest.startDate) ? current : latest;
25
+ });
26
+ }
27
+ function getPrimaryPurchase(purchases) {
28
+ const filtered = filterPurchases(purchases);
29
+ if (filtered.length > 0) {
30
+ return getMostRecentPurchase(filtered);
31
+ }
32
+ return null;
33
+ }
34
+ function isPaidPurchase(purchase) {
35
+ return (purchase.amount ?? 0) > 0;
36
+ }
37
+
38
+ // src/SolvaPayProvider.tsx
39
+ import { jsx } from "react/jsx-runtime";
40
+ var SolvaPayContext = createContext(null);
41
+ var CUSTOMER_REF_KEY = "solvapay_customerRef";
42
+ var CUSTOMER_REF_EXPIRY = "solvapay_customerRef_expiry";
43
+ var CUSTOMER_REF_USER_ID_KEY = "solvapay_customerRef_userId";
44
+ var CACHE_DURATION = 24 * 60 * 60 * 1e3;
45
+ function getCachedCustomerRef(userId) {
46
+ if (typeof window === "undefined") return null;
47
+ const cached = localStorage.getItem(CUSTOMER_REF_KEY);
48
+ const expiry = localStorage.getItem(CUSTOMER_REF_EXPIRY);
49
+ const cachedUserId = localStorage.getItem(CUSTOMER_REF_USER_ID_KEY);
50
+ if (!cached || !expiry) return null;
51
+ if (Date.now() > parseInt(expiry)) {
52
+ localStorage.removeItem(CUSTOMER_REF_KEY);
53
+ localStorage.removeItem(CUSTOMER_REF_EXPIRY);
54
+ localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
55
+ return null;
56
+ }
57
+ if (userId !== void 0 && userId !== null) {
58
+ if (cachedUserId !== userId) {
59
+ clearCachedCustomerRef();
60
+ return null;
61
+ }
62
+ }
63
+ return cached;
64
+ }
65
+ function setCachedCustomerRef(customerRef, userId) {
66
+ if (typeof window === "undefined") return;
67
+ if (userId === void 0 || userId === null) {
68
+ return;
69
+ }
70
+ localStorage.setItem(CUSTOMER_REF_KEY, customerRef);
71
+ localStorage.setItem(CUSTOMER_REF_EXPIRY, String(Date.now() + CACHE_DURATION));
72
+ localStorage.setItem(CUSTOMER_REF_USER_ID_KEY, userId);
73
+ }
74
+ function clearCachedCustomerRef() {
75
+ if (typeof window === "undefined") return;
76
+ localStorage.removeItem(CUSTOMER_REF_KEY);
77
+ localStorage.removeItem(CUSTOMER_REF_EXPIRY);
78
+ localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
79
+ }
80
+ function getAuthAdapter(config) {
81
+ if (config?.auth?.adapter) {
82
+ return config.auth.adapter;
83
+ }
84
+ if (config?.auth?.getToken || config?.auth?.getUserId) {
85
+ return {
86
+ async getToken() {
87
+ return config?.auth?.getToken?.() || null;
88
+ },
89
+ async getUserId() {
90
+ return config?.auth?.getUserId?.() || null;
91
+ }
92
+ };
93
+ }
94
+ return defaultAuthAdapter;
95
+ }
6
96
  var SolvaPayProvider = ({
7
- children,
8
- amount = 999,
9
- // Default $9.99
10
- currency = "USD",
11
- planRef,
12
- agentRef,
13
- apiBaseUrl = "/api/solvapay",
14
- onPaymentReady
97
+ config,
98
+ createPayment: customCreatePayment,
99
+ checkPurchase: customCheckPurchase,
100
+ processPayment: customProcessPayment,
101
+ children
15
102
  }) => {
16
- const [stripePromise, setStripePromise] = useState(null);
17
- const [clientSecret, setClientSecret] = useState("");
103
+ const [purchaseData, setPurchaseData] = useState({
104
+ purchases: []
105
+ });
18
106
  const [loading, setLoading] = useState(false);
19
- const [error, setError] = useState(null);
20
- const createPayment = async (paymentAmount) => {
21
- setLoading(true);
22
- setError(null);
23
- try {
24
- console.log("Creating SolvaPay payment intent for amount:", paymentAmount);
25
- const response = await fetch(`${apiBaseUrl}/create-payment-intent`, {
107
+ const [internalCustomerRef, setInternalCustomerRef] = useState(void 0);
108
+ const [userId, setUserId] = useState(null);
109
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
110
+ const inFlightRef = useRef(null);
111
+ const lastFetchedRef = useRef(null);
112
+ const checkPurchaseRef = useRef(null);
113
+ const createPaymentRef = useRef(null);
114
+ const processPaymentRef = useRef(null);
115
+ const configRef = useRef(config);
116
+ const buildDefaultCheckPurchaseRef = useRef(
117
+ null
118
+ );
119
+ useEffect(() => {
120
+ configRef.current = config;
121
+ }, [config]);
122
+ useEffect(() => {
123
+ checkPurchaseRef.current = customCheckPurchase || null;
124
+ }, [customCheckPurchase]);
125
+ useEffect(() => {
126
+ createPaymentRef.current = customCreatePayment || null;
127
+ }, [customCreatePayment]);
128
+ useEffect(() => {
129
+ processPaymentRef.current = customProcessPayment || null;
130
+ }, [customProcessPayment]);
131
+ const buildDefaultCheckPurchase = useCallback(async () => {
132
+ const currentConfig = configRef.current;
133
+ const adapter = getAuthAdapter(currentConfig);
134
+ const token = await adapter.getToken();
135
+ const detectedUserId = await adapter.getUserId();
136
+ const route = currentConfig?.api?.checkPurchase || "/api/check-purchase";
137
+ const fetchFn = currentConfig?.fetch || fetch;
138
+ const cachedRef = getCachedCustomerRef(detectedUserId);
139
+ const headers = {
140
+ "Content-Type": "application/json"
141
+ };
142
+ if (token) {
143
+ headers["Authorization"] = `Bearer ${token}`;
144
+ }
145
+ if (cachedRef) {
146
+ headers["x-solvapay-customer-ref"] = cachedRef;
147
+ }
148
+ if (currentConfig?.headers) {
149
+ const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
150
+ Object.assign(headers, customHeaders);
151
+ }
152
+ const res = await fetchFn(route, {
153
+ method: "GET",
154
+ headers
155
+ });
156
+ if (!res.ok) {
157
+ const error = new Error(`Failed to check purchase: ${res.statusText}`);
158
+ currentConfig?.onError?.(error, "checkPurchase");
159
+ throw error;
160
+ }
161
+ return res.json();
162
+ }, []);
163
+ useEffect(() => {
164
+ buildDefaultCheckPurchaseRef.current = buildDefaultCheckPurchase;
165
+ }, [buildDefaultCheckPurchase]);
166
+ const buildDefaultCreatePayment = useCallback(
167
+ async (params) => {
168
+ const currentConfig = configRef.current;
169
+ const adapter = getAuthAdapter(currentConfig);
170
+ const token = await adapter.getToken();
171
+ const detectedUserId = await adapter.getUserId();
172
+ const route = currentConfig?.api?.createPayment || "/api/create-payment-intent";
173
+ const fetchFn = currentConfig?.fetch || fetch;
174
+ const cachedRef = getCachedCustomerRef(detectedUserId);
175
+ const headers = {
176
+ "Content-Type": "application/json"
177
+ };
178
+ if (token) {
179
+ headers["Authorization"] = `Bearer ${token}`;
180
+ }
181
+ if (cachedRef) {
182
+ headers["x-solvapay-customer-ref"] = cachedRef;
183
+ }
184
+ if (currentConfig?.headers) {
185
+ const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
186
+ Object.assign(headers, customHeaders);
187
+ }
188
+ const body = { planRef: params.planRef };
189
+ if (params.productRef) {
190
+ body.productRef = params.productRef;
191
+ }
192
+ const res = await fetchFn(route, {
26
193
  method: "POST",
27
- headers: {
28
- "Content-Type": "application/json"
29
- },
30
- body: JSON.stringify({
31
- planRef,
32
- agentRef,
33
- amount: paymentAmount,
34
- currency,
35
- description: "SolvaPay - Plan Purchase"
36
- })
194
+ headers,
195
+ body: JSON.stringify(body)
37
196
  });
38
- if (!response.ok) {
39
- const errorText = await response.text();
40
- throw new Error(`Payment intent creation failed: ${response.status} ${errorText}`);
41
- }
42
- const result = await response.json();
43
- if (!result || !result.clientSecret || !result.publishableKey) {
44
- throw new Error("Invalid response from server: missing required fields");
45
- }
46
- console.log("Payment intent received:", {
47
- hasClientSecret: !!result.clientSecret,
48
- hasPublishableKey: !!result.publishableKey,
49
- hasAccountId: !!result.accountId,
50
- clientSecretLength: result.clientSecret?.length || 0,
51
- publishableKeyLength: result.publishableKey?.length || 0
197
+ if (!res.ok) {
198
+ const error = new Error(`Failed to create payment: ${res.statusText}`);
199
+ currentConfig?.onError?.(error, "createPayment");
200
+ throw error;
201
+ }
202
+ return res.json();
203
+ },
204
+ []
205
+ );
206
+ const buildDefaultProcessPayment = useCallback(
207
+ async (params) => {
208
+ const currentConfig = configRef.current;
209
+ const adapter = getAuthAdapter(currentConfig);
210
+ const token = await adapter.getToken();
211
+ const detectedUserId = await adapter.getUserId();
212
+ const route = currentConfig?.api?.processPayment || "/api/process-payment";
213
+ const fetchFn = currentConfig?.fetch || fetch;
214
+ const cachedRef = getCachedCustomerRef(detectedUserId);
215
+ const headers = {
216
+ "Content-Type": "application/json"
217
+ };
218
+ if (token) {
219
+ headers["Authorization"] = `Bearer ${token}`;
220
+ }
221
+ if (cachedRef) {
222
+ headers["x-solvapay-customer-ref"] = cachedRef;
223
+ }
224
+ if (currentConfig?.headers) {
225
+ const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
226
+ Object.assign(headers, customHeaders);
227
+ }
228
+ const res = await fetchFn(route, {
229
+ method: "POST",
230
+ headers,
231
+ body: JSON.stringify(params)
52
232
  });
233
+ if (!res.ok) {
234
+ const error = new Error(`Failed to process payment: ${res.statusText}`);
235
+ currentConfig?.onError?.(error, "processPayment");
236
+ throw error;
237
+ }
238
+ return res.json();
239
+ },
240
+ []
241
+ );
242
+ const _checkPurchase = useCallback(async () => {
243
+ if (checkPurchaseRef.current) {
244
+ return checkPurchaseRef.current();
245
+ }
246
+ if (buildDefaultCheckPurchaseRef.current) {
247
+ return buildDefaultCheckPurchaseRef.current();
248
+ }
249
+ return buildDefaultCheckPurchase();
250
+ }, [buildDefaultCheckPurchase]);
251
+ const createPayment = useCallback(
252
+ async (params) => {
253
+ if (createPaymentRef.current) {
254
+ return createPaymentRef.current(params);
255
+ }
256
+ return buildDefaultCreatePayment(params);
257
+ },
258
+ [buildDefaultCreatePayment]
259
+ );
260
+ const processPayment = useCallback(
261
+ async (params) => {
262
+ if (processPaymentRef.current) {
263
+ return processPaymentRef.current(params);
264
+ }
265
+ return buildDefaultProcessPayment(params);
266
+ },
267
+ [buildDefaultProcessPayment]
268
+ );
269
+ useEffect(() => {
270
+ const detectAuth = async () => {
271
+ const currentConfig = configRef.current;
272
+ const adapter = getAuthAdapter(currentConfig);
273
+ const token = await adapter.getToken();
274
+ const detectedUserId = await adapter.getUserId();
275
+ const prevUserId = userId;
276
+ setIsAuthenticated(!!token);
277
+ setUserId(detectedUserId);
278
+ if (prevUserId !== null && detectedUserId !== prevUserId) {
279
+ clearCachedCustomerRef();
280
+ setInternalCustomerRef(void 0);
281
+ return;
282
+ }
283
+ const cachedRef = getCachedCustomerRef(detectedUserId);
284
+ if (cachedRef && token) {
285
+ setInternalCustomerRef(cachedRef);
286
+ } else if (!token) {
287
+ clearCachedCustomerRef();
288
+ setInternalCustomerRef(void 0);
289
+ } else if (token && !cachedRef) {
290
+ setInternalCustomerRef(void 0);
291
+ }
292
+ };
293
+ detectAuth();
294
+ const interval = setInterval(detectAuth, 5e3);
295
+ return () => clearInterval(interval);
296
+ }, [userId]);
297
+ const fetchPurchase = useCallback(
298
+ async (force = false) => {
299
+ if (!isAuthenticated && !internalCustomerRef) {
300
+ setPurchaseData({ purchases: [] });
301
+ setLoading(false);
302
+ inFlightRef.current = null;
303
+ lastFetchedRef.current = null;
304
+ return;
305
+ }
306
+ const cacheKey = internalCustomerRef || userId || "anonymous";
307
+ if (!force && lastFetchedRef.current === cacheKey && inFlightRef.current !== cacheKey) {
308
+ return;
309
+ }
310
+ if (inFlightRef.current === cacheKey) {
311
+ return;
312
+ }
313
+ inFlightRef.current = cacheKey;
314
+ setLoading(true);
315
+ try {
316
+ const checkFn = checkPurchaseRef.current || buildDefaultCheckPurchaseRef.current;
317
+ if (!checkFn) {
318
+ throw new Error("checkPurchase function not available");
319
+ }
320
+ const data = await checkFn();
321
+ if (data.customerRef) {
322
+ setInternalCustomerRef(data.customerRef);
323
+ const currentAdapter = getAuthAdapter(configRef.current);
324
+ const currentUserId = await currentAdapter.getUserId();
325
+ setCachedCustomerRef(data.customerRef, currentUserId);
326
+ }
327
+ if (inFlightRef.current === cacheKey) {
328
+ const filteredData = {
329
+ ...data,
330
+ purchases: filterPurchases(data.purchases || [])
331
+ };
332
+ setPurchaseData(filteredData);
333
+ lastFetchedRef.current = cacheKey;
334
+ }
335
+ } catch (error) {
336
+ console.error("[SolvaPayProvider] Failed to fetch purchase:", error);
337
+ if (inFlightRef.current === cacheKey) {
338
+ setPurchaseData({
339
+ purchases: []
340
+ });
341
+ lastFetchedRef.current = cacheKey;
342
+ }
343
+ } finally {
344
+ if (inFlightRef.current === cacheKey) {
345
+ setLoading(false);
346
+ inFlightRef.current = null;
347
+ }
348
+ }
349
+ },
350
+ [isAuthenticated, internalCustomerRef, userId]
351
+ );
352
+ const fetchPurchaseRef = useRef(fetchPurchase);
353
+ useEffect(() => {
354
+ fetchPurchaseRef.current = fetchPurchase;
355
+ }, [fetchPurchase]);
356
+ const refetchPurchase = useCallback(async () => {
357
+ lastFetchedRef.current = null;
358
+ inFlightRef.current = null;
359
+ setPurchaseData({ purchases: [] });
360
+ await fetchPurchaseRef.current(true);
361
+ }, []);
362
+ useEffect(() => {
363
+ lastFetchedRef.current = null;
364
+ inFlightRef.current = null;
365
+ if (isAuthenticated || internalCustomerRef) {
366
+ fetchPurchase();
367
+ } else {
368
+ setPurchaseData({ purchases: [] });
369
+ setLoading(false);
370
+ }
371
+ }, [isAuthenticated, internalCustomerRef, userId]);
372
+ const updateCustomerRef = useCallback(
373
+ (newCustomerRef) => {
374
+ setInternalCustomerRef(newCustomerRef);
375
+ setCachedCustomerRef(newCustomerRef, userId);
376
+ fetchPurchase(true);
377
+ },
378
+ [fetchPurchase, userId]
379
+ );
380
+ const purchase = useMemo(() => {
381
+ const activePurchase = getPrimaryPurchase(purchaseData.purchases);
382
+ const activePaidPurchases = purchaseData.purchases.filter(
383
+ (p) => p.status === "active" && isPaidPurchase(p)
384
+ );
385
+ const activePaidPurchase = activePaidPurchases.sort(
386
+ (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
387
+ )[0] || null;
388
+ return {
389
+ loading,
390
+ customerRef: purchaseData.customerRef || internalCustomerRef,
391
+ email: purchaseData.email,
392
+ name: purchaseData.name,
393
+ purchases: purchaseData.purchases,
394
+ hasPlan: (planName) => {
395
+ return purchaseData.purchases.some(
396
+ (p) => p.planName.toLowerCase() === planName.toLowerCase() && p.status === "active"
397
+ );
398
+ },
399
+ activePurchase,
400
+ hasPaidPurchase: activePaidPurchases.length > 0,
401
+ activePaidPurchase
402
+ };
403
+ }, [loading, purchaseData, internalCustomerRef]);
404
+ const contextValue = useMemo(
405
+ () => ({
406
+ purchase,
407
+ refetchPurchase,
408
+ createPayment,
409
+ processPayment,
410
+ customerRef: purchaseData.customerRef || internalCustomerRef,
411
+ updateCustomerRef
412
+ }),
413
+ [
414
+ purchase,
415
+ refetchPurchase,
416
+ createPayment,
417
+ processPayment,
418
+ purchaseData.customerRef,
419
+ internalCustomerRef,
420
+ updateCustomerRef
421
+ ]
422
+ );
423
+ return /* @__PURE__ */ jsx(SolvaPayContext.Provider, { value: contextValue, children });
424
+ };
425
+
426
+ // src/PaymentForm.tsx
427
+ import { useEffect as useEffect2, useCallback as useCallback3, useRef as useRef3, useMemo as useMemo2, useState as useState4 } from "react";
428
+ import { Elements } from "@stripe/react-stripe-js";
429
+
430
+ // src/hooks/useCheckout.ts
431
+ import { useState as useState2, useCallback as useCallback2, useRef as useRef2 } from "react";
432
+ import { loadStripe } from "@stripe/stripe-js";
433
+
434
+ // src/hooks/useSolvaPay.ts
435
+ import { useContext } from "react";
436
+ function useSolvaPay() {
437
+ const context = useContext(SolvaPayContext);
438
+ if (!context) {
439
+ throw new Error(
440
+ "useSolvaPay must be used within a SolvaPayProvider. Wrap your component tree with <SolvaPayProvider> to use this hook."
441
+ );
442
+ }
443
+ return context;
444
+ }
445
+
446
+ // src/hooks/useCheckout.ts
447
+ var stripePromiseCache = /* @__PURE__ */ new Map();
448
+ function getStripeCacheKey(publishableKey, accountId) {
449
+ return accountId ? `${publishableKey}:${accountId}` : publishableKey;
450
+ }
451
+ function useCheckout(options) {
452
+ const { planRef, productRef } = options;
453
+ const { createPayment, customerRef, updateCustomerRef } = useSolvaPay();
454
+ const [loading, setLoading] = useState2(false);
455
+ const [error, setError] = useState2(
456
+ !planRef || typeof planRef !== "string" ? new Error("useCheckout: planRef parameter is required and must be a string") : null
457
+ );
458
+ const [stripePromise, setStripePromise] = useState2(null);
459
+ const [clientSecret, setClientSecret] = useState2(null);
460
+ const isStartingRef = useRef2(false);
461
+ const startCheckout = useCallback2(async () => {
462
+ if (isStartingRef.current || loading) {
463
+ return;
464
+ }
465
+ if (!planRef || typeof planRef !== "string") {
466
+ setError(new Error("useCheckout: planRef parameter is required and must be a string"));
467
+ return;
468
+ }
469
+ isStartingRef.current = true;
470
+ setLoading(true);
471
+ setError(null);
472
+ try {
473
+ const result = await createPayment({ planRef, productRef });
474
+ if (!result || typeof result !== "object") {
475
+ throw new Error("Invalid payment intent response from server");
476
+ }
477
+ if (!result.clientSecret || typeof result.clientSecret !== "string") {
478
+ throw new Error("Invalid client secret in payment intent response");
479
+ }
480
+ if (!result.publishableKey || typeof result.publishableKey !== "string") {
481
+ throw new Error("Invalid publishable key in payment intent response");
482
+ }
483
+ if (result.customerRef && result.customerRef !== customerRef && updateCustomerRef) {
484
+ updateCustomerRef(result.customerRef);
485
+ }
53
486
  const stripeOptions = result.accountId ? { stripeAccount: result.accountId } : {};
54
- const stripe = await loadStripe(result.publishableKey, stripeOptions);
487
+ const cacheKey = getStripeCacheKey(result.publishableKey, result.accountId);
488
+ let stripe = stripePromiseCache.get(cacheKey);
55
489
  if (!stripe) {
56
- throw new Error("Failed to initialize Stripe. Please check your configuration.");
490
+ stripe = loadStripe(result.publishableKey, stripeOptions);
491
+ stripePromiseCache.set(cacheKey, stripe);
57
492
  }
58
493
  setStripePromise(stripe);
59
494
  setClientSecret(result.clientSecret);
60
- if (onPaymentReady) {
61
- onPaymentReady(stripe, result.clientSecret);
62
- }
63
- } catch (error2) {
64
- console.error("Failed to create payment:", error2);
65
- let errorMessage = "Payment creation failed";
66
- if (error2 instanceof Error) {
67
- if (error2.message.includes("publishable key")) {
68
- errorMessage = "Server configuration error: Missing Stripe publishable key";
69
- } else if (error2.message.includes("client secret")) {
70
- errorMessage = "Server error: Payment intent creation failed";
71
- } else if (error2.message.includes("Failed to initialize Stripe")) {
72
- errorMessage = "Stripe initialization failed. Please check your configuration.";
73
- } else {
74
- errorMessage = error2.message;
75
- }
76
- }
77
- setError(errorMessage);
495
+ } catch (err) {
496
+ const error2 = err instanceof Error ? err : new Error("Failed to start checkout");
497
+ setError(error2);
78
498
  } finally {
79
499
  setLoading(false);
500
+ isStartingRef.current = false;
80
501
  }
502
+ }, [planRef, productRef, createPayment, updateCustomerRef, loading]);
503
+ const reset = useCallback2(() => {
504
+ isStartingRef.current = false;
505
+ setLoading(false);
506
+ setError(null);
507
+ setStripePromise(null);
508
+ setClientSecret(null);
509
+ }, []);
510
+ return {
511
+ loading,
512
+ error,
513
+ stripePromise,
514
+ clientSecret,
515
+ startCheckout,
516
+ reset
81
517
  };
82
- useEffect(() => {
83
- if (amount && !stripePromise && !loading && !error) {
84
- createPayment(amount);
85
- }
86
- }, [amount]);
87
- if (error) {
88
- return /* @__PURE__ */ jsxs("div", { style: {
89
- padding: "1rem",
90
- backgroundColor: "#fed7d7",
91
- color: "#742a2a",
92
- borderRadius: "0.375rem",
93
- marginBottom: "1rem"
94
- }, children: [
95
- /* @__PURE__ */ jsx("strong", { children: "Payment Setup Error:" }),
96
- " ",
97
- error,
98
- /* @__PURE__ */ jsx(
99
- "button",
100
- {
101
- onClick: () => createPayment(amount),
102
- style: {
103
- marginLeft: "1rem",
104
- padding: "0.5rem 1rem",
105
- backgroundColor: "#742a2a",
106
- color: "white",
107
- border: "none",
108
- borderRadius: "0.25rem",
109
- cursor: "pointer"
110
- },
111
- children: "Retry"
112
- }
113
- )
114
- ] });
115
- }
116
- if (loading) {
117
- return /* @__PURE__ */ jsx("div", { style: {
118
- padding: "1rem",
119
- textAlign: "center",
120
- color: "#4a5568"
121
- }, children: "Setting up payment..." });
122
- }
123
- if (!stripePromise || !clientSecret) {
124
- return /* @__PURE__ */ jsx("div", { style: {
125
- padding: "1rem",
126
- textAlign: "center",
127
- color: "#4a5568"
128
- }, children: /* @__PURE__ */ jsx(
129
- "button",
130
- {
131
- onClick: () => createPayment(amount),
132
- style: {
133
- padding: "0.75rem 1.5rem",
134
- backgroundColor: "#3182ce",
135
- color: "white",
136
- border: "none",
137
- borderRadius: "0.375rem",
138
- cursor: "pointer",
139
- fontSize: "1rem"
140
- },
141
- children: "Initialize Payment"
142
- }
143
- ) });
144
- }
145
- return /* @__PURE__ */ jsx(Elements, { stripe: stripePromise, options: { clientSecret }, children });
518
+ }
519
+
520
+ // src/hooks/usePurchase.ts
521
+ function usePurchase() {
522
+ const { purchase, refetchPurchase } = useSolvaPay();
523
+ return {
524
+ ...purchase,
525
+ refetch: refetchPurchase
526
+ };
527
+ }
528
+
529
+ // src/components/Spinner.tsx
530
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
531
+ var Spinner = ({
532
+ className = "",
533
+ size = "md"
534
+ }) => {
535
+ const sizeClasses = {
536
+ sm: "h-4 w-4",
537
+ md: "h-5 w-5",
538
+ lg: "h-6 w-6"
539
+ };
540
+ return /* @__PURE__ */ jsxs(
541
+ "svg",
542
+ {
543
+ className: `animate-spin ${sizeClasses[size]} ${className}`,
544
+ xmlns: "http://www.w3.org/2000/svg",
545
+ fill: "none",
546
+ viewBox: "0 0 24 24",
547
+ role: "status",
548
+ "aria-busy": "true",
549
+ children: [
550
+ /* @__PURE__ */ jsx2("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
551
+ /* @__PURE__ */ jsx2(
552
+ "path",
553
+ {
554
+ className: "opacity-75",
555
+ fill: "currentColor",
556
+ 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"
557
+ }
558
+ )
559
+ ]
560
+ }
561
+ );
146
562
  };
147
563
 
148
- // src/PaymentForm.tsx
149
- import { useState as useState2 } from "react";
150
- import { useStripe, useElements, PaymentElement } from "@stripe/react-stripe-js";
151
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
152
- var PaymentForm = ({
564
+ // src/components/StripePaymentFormWrapper.tsx
565
+ import { useState as useState3 } from "react";
566
+ import { useStripe, useElements, CardElement } from "@stripe/react-stripe-js";
567
+
568
+ // src/hooks/useCustomer.ts
569
+ function useCustomer() {
570
+ const { purchase, customerRef } = useSolvaPay();
571
+ return {
572
+ customerRef: purchase.customerRef || customerRef,
573
+ email: purchase.email,
574
+ name: purchase.name,
575
+ loading: purchase.loading
576
+ };
577
+ }
578
+
579
+ // src/components/StripePaymentFormWrapper.tsx
580
+ import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
581
+ var StripePaymentFormWrapper = ({
153
582
  onSuccess,
154
583
  onError,
155
- returnUrl,
584
+ returnUrl: _returnUrl,
156
585
  submitButtonText = "Pay Now",
157
- className
586
+ buttonClassName,
587
+ clientSecret
158
588
  }) => {
159
589
  const stripe = useStripe();
160
590
  const elements = useElements();
161
- const [isProcessing, setIsProcessing] = useState2(false);
162
- const [message, setMessage] = useState2(null);
591
+ const customer = useCustomer();
592
+ const [isProcessing, setIsProcessing] = useState3(false);
593
+ const [message, setMessage] = useState3(null);
594
+ const [cardComplete, setCardComplete] = useState3(false);
163
595
  const handleSubmit = async (event) => {
164
596
  event.preventDefault();
165
597
  if (!stripe || !elements) {
598
+ const errorMessage = "Stripe is not available. Please refresh the page.";
599
+ setMessage(errorMessage);
600
+ if (onError) {
601
+ onError(new Error(errorMessage));
602
+ }
603
+ return;
604
+ }
605
+ if (!clientSecret) {
606
+ const errorMessage = "Payment intent not available. Please refresh the page.";
607
+ setMessage(errorMessage);
608
+ if (onError) {
609
+ onError(new Error(errorMessage));
610
+ }
166
611
  return;
167
612
  }
168
613
  setIsProcessing(true);
169
614
  setMessage(null);
170
615
  try {
171
- const { error, paymentIntent } = await stripe.confirmPayment({
172
- elements,
173
- confirmParams: {
174
- return_url: returnUrl || `${window.location.origin}/checkout/complete`
175
- },
176
- redirect: "if_required"
177
- // Only redirect if required by payment method
616
+ const cardElement = elements.getElement(CardElement);
617
+ if (!cardElement) {
618
+ const errorMessage = "Card element not found";
619
+ setMessage(errorMessage);
620
+ setIsProcessing(false);
621
+ if (onError) {
622
+ onError(new Error(errorMessage));
623
+ }
624
+ return;
625
+ }
626
+ const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
627
+ payment_method: {
628
+ card: cardElement,
629
+ billing_details: {
630
+ email: customer.email,
631
+ name: customer.name
632
+ }
633
+ }
178
634
  });
179
635
  if (error) {
180
636
  const errorMessage = error.message || "An unexpected error occurred.";
181
637
  setMessage(errorMessage);
638
+ setIsProcessing(false);
182
639
  if (onError) {
183
640
  onError(new Error(errorMessage));
184
641
  }
185
642
  } else if (paymentIntent && paymentIntent.status === "succeeded") {
186
- setMessage("Payment successful!");
643
+ setMessage(null);
187
644
  if (onSuccess) {
188
- onSuccess(paymentIntent);
645
+ try {
646
+ await onSuccess(paymentIntent);
647
+ setMessage("Payment successful!");
648
+ } catch (err) {
649
+ const error2 = err instanceof Error ? err : new Error("Payment processing failed");
650
+ setMessage("Payment processing failed. Please try again or contact support.");
651
+ setIsProcessing(false);
652
+ if (onError) {
653
+ onError(error2);
654
+ }
655
+ return;
656
+ }
657
+ } else {
658
+ setMessage("Payment successful!");
189
659
  }
190
- } else {
191
- setMessage(`Payment status: ${paymentIntent?.status || "processing"}`);
660
+ } else if (paymentIntent && paymentIntent.status === "requires_action") {
661
+ setMessage("Payment requires additional authentication. Please complete the verification.");
662
+ setIsProcessing(false);
663
+ } else if (paymentIntent) {
664
+ setMessage(`Payment status: ${paymentIntent.status || "processing"}`);
665
+ setIsProcessing(false);
192
666
  }
193
667
  } catch (err) {
194
668
  const error = err instanceof Error ? err : new Error("Unknown error occurred");
@@ -200,45 +674,574 @@ var PaymentForm = ({
200
674
  setIsProcessing(false);
201
675
  }
202
676
  };
203
- return /* @__PURE__ */ jsxs2("form", { onSubmit: handleSubmit, className, children: [
204
- /* @__PURE__ */ jsx2(PaymentElement, {}),
205
- message && /* @__PURE__ */ jsx2(
677
+ const isSuccess = message?.includes("successful") ?? false;
678
+ const isReady = !!(stripe && elements);
679
+ const cardElementOptions = {
680
+ style: {
681
+ base: {
682
+ fontSize: "16px",
683
+ color: "#424770",
684
+ "::placeholder": {
685
+ color: "#aab7c4"
686
+ }
687
+ },
688
+ invalid: {
689
+ color: "#9e2146"
690
+ }
691
+ },
692
+ hidePostalCode: true
693
+ };
694
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
695
+ isReady ? /* @__PURE__ */ jsx3(
696
+ CardElement,
697
+ {
698
+ options: cardElementOptions,
699
+ onChange: (e) => {
700
+ if (e.error) {
701
+ setMessage(e.error.message);
702
+ setCardComplete(false);
703
+ } else {
704
+ setMessage(null);
705
+ setCardComplete(e.complete);
706
+ }
707
+ }
708
+ }
709
+ ) : /* @__PURE__ */ jsx3(
206
710
  "div",
207
711
  {
208
712
  style: {
209
- marginTop: "1rem",
210
- padding: "0.75rem",
713
+ padding: "12px",
714
+ border: "1px solid #cbd5e1",
211
715
  borderRadius: "0.375rem",
212
- backgroundColor: message.includes("successful") ? "#d1fae5" : "#fee2e2",
213
- color: message.includes("successful") ? "#065f46" : "#7f1d1d"
716
+ backgroundColor: "white",
717
+ display: "flex",
718
+ alignItems: "center",
719
+ justifyContent: "center",
720
+ minHeight: "40px"
214
721
  },
215
- children: message
722
+ children: /* @__PURE__ */ jsx3(Spinner, { size: "sm" })
216
723
  }
217
724
  ),
218
- /* @__PURE__ */ jsx2(
725
+ message && !isSuccess && /* @__PURE__ */ jsx3("div", { role: "alert", "aria-live": "assertive", "aria-atomic": "true", children: message }),
726
+ /* @__PURE__ */ jsx3(
219
727
  "button",
220
728
  {
221
729
  type: "submit",
222
- disabled: !stripe || isProcessing,
223
- style: {
224
- marginTop: "1.5rem",
225
- width: "100%",
226
- padding: "0.75rem 1.5rem",
227
- backgroundColor: isProcessing || !stripe ? "#9ca3af" : "#3b82f6",
228
- color: "white",
229
- border: "none",
230
- borderRadius: "0.375rem",
231
- fontSize: "1rem",
232
- fontWeight: "500",
233
- cursor: isProcessing || !stripe ? "not-allowed" : "pointer",
234
- transition: "background-color 0.2s"
235
- },
236
- children: isProcessing ? "Processing..." : submitButtonText
730
+ disabled: !isReady || !cardComplete || isProcessing || !clientSecret,
731
+ className: buttonClassName,
732
+ "aria-busy": isProcessing,
733
+ "aria-disabled": !isReady || !cardComplete || isProcessing || !clientSecret,
734
+ onClick: handleSubmit,
735
+ children: isProcessing ? /* @__PURE__ */ jsxs2(Fragment, { children: [
736
+ /* @__PURE__ */ jsx3(Spinner, { size: "sm" }),
737
+ /* @__PURE__ */ jsx3("span", { children: "Processing..." })
738
+ ] }) : submitButtonText
237
739
  }
238
740
  )
239
741
  ] });
240
742
  };
743
+
744
+ // src/PaymentForm.tsx
745
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
746
+ var PaymentForm = ({
747
+ planRef,
748
+ productRef,
749
+ onSuccess,
750
+ onError,
751
+ returnUrl,
752
+ submitButtonText = "Pay Now",
753
+ className,
754
+ buttonClassName
755
+ }) => {
756
+ const validPlanRef = planRef && typeof planRef === "string" ? planRef : "";
757
+ const {
758
+ loading: checkoutLoading,
759
+ error: checkoutError,
760
+ clientSecret,
761
+ startCheckout,
762
+ stripePromise
763
+ } = useCheckout({ planRef: validPlanRef, productRef });
764
+ const { refetch } = usePurchase();
765
+ const { processPayment } = useSolvaPay();
766
+ const hasInitializedRef = useRef3(false);
767
+ useEffect2(() => {
768
+ if (!hasInitializedRef.current && validPlanRef && !checkoutLoading && !checkoutError && !clientSecret) {
769
+ hasInitializedRef.current = true;
770
+ startCheckout().catch(() => {
771
+ hasInitializedRef.current = false;
772
+ });
773
+ }
774
+ if (validPlanRef && clientSecret) {
775
+ hasInitializedRef.current = true;
776
+ }
777
+ }, [validPlanRef, checkoutLoading, checkoutError, clientSecret, startCheckout]);
778
+ const handleSuccess = useCallback3(
779
+ async (paymentIntent) => {
780
+ let processingTimeout = false;
781
+ let processingResult = null;
782
+ const paymentIntentAny = paymentIntent;
783
+ if (processPayment && productRef) {
784
+ try {
785
+ const result = await processPayment({
786
+ paymentIntentId: paymentIntentAny.id,
787
+ productRef,
788
+ planRef
789
+ });
790
+ processingResult = result;
791
+ const isTimeout = result?.status === "timeout";
792
+ processingTimeout = isTimeout;
793
+ if (isTimeout) {
794
+ for (let attempt = 1; attempt <= 5; attempt++) {
795
+ const delay = attempt * 1e3;
796
+ await new Promise((resolve) => setTimeout(resolve, delay));
797
+ await refetch();
798
+ }
799
+ if (onSuccess) {
800
+ await onSuccess({
801
+ ...paymentIntentAny,
802
+ _processingTimeout: processingTimeout,
803
+ _processingResult: processingResult
804
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
805
+ });
806
+ }
807
+ throw new Error("Payment processing timed out");
808
+ } else {
809
+ await refetch();
810
+ }
811
+ } catch (error) {
812
+ console.error("[PaymentForm] Failed to process payment:", error);
813
+ if (onSuccess) {
814
+ try {
815
+ await onSuccess({
816
+ ...paymentIntentAny,
817
+ _processingError: error
818
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
819
+ });
820
+ } catch {
821
+ }
822
+ }
823
+ throw error;
824
+ }
825
+ } else {
826
+ await refetch();
827
+ }
828
+ if (onSuccess && !processingTimeout) {
829
+ await onSuccess({
830
+ ...paymentIntentAny,
831
+ _processingTimeout: processingTimeout,
832
+ _processingResult: processingResult
833
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
834
+ });
835
+ }
836
+ },
837
+ [processPayment, productRef, planRef, refetch, onSuccess]
838
+ );
839
+ const handleError = useCallback3(
840
+ (err) => {
841
+ if (onError) {
842
+ onError(err);
843
+ }
844
+ },
845
+ [onError]
846
+ );
847
+ const finalReturnUrl = returnUrl || (typeof window !== "undefined" ? window.location.href : "/");
848
+ const isValidPlanRef = planRef && typeof planRef === "string";
849
+ const hasError = !!checkoutError;
850
+ const hasStripeData = !!(stripePromise && clientSecret);
851
+ const elementsOptions = useMemo2(() => {
852
+ if (!clientSecret) return void 0;
853
+ return { clientSecret };
854
+ }, [clientSecret]);
855
+ const [hasMountedElements, setHasMountedElements] = useState4(false);
856
+ useEffect2(() => {
857
+ if (hasStripeData) {
858
+ setHasMountedElements(true);
859
+ }
860
+ }, [hasStripeData]);
861
+ const shouldRenderElements = hasStripeData || hasMountedElements && stripePromise && clientSecret;
862
+ return /* @__PURE__ */ jsx4("div", { className, children: !isValidPlanRef ? /* @__PURE__ */ jsx4("div", { children: "PaymentForm: planRef is required and must be a string" }) : hasError ? /* @__PURE__ */ jsxs3("div", { children: [
863
+ /* @__PURE__ */ jsx4("div", { children: "Payment initialization failed" }),
864
+ /* @__PURE__ */ jsx4("div", { children: checkoutError?.message || "Unknown error" })
865
+ ] }) : shouldRenderElements && elementsOptions ? (
866
+ // Once we have Stripe data, always render Elements to maintain hook consistency
867
+ // This prevents hook count mismatches when transitioning between states
868
+ /* @__PURE__ */ jsx4(
869
+ Elements,
870
+ {
871
+ stripe: stripePromise,
872
+ options: elementsOptions,
873
+ children: /* @__PURE__ */ jsx4(
874
+ StripePaymentFormWrapper,
875
+ {
876
+ onSuccess: handleSuccess,
877
+ onError: handleError,
878
+ returnUrl: finalReturnUrl,
879
+ submitButtonText,
880
+ buttonClassName,
881
+ clientSecret
882
+ }
883
+ )
884
+ },
885
+ clientSecret
886
+ )
887
+ ) : (
888
+ // Loading state before Stripe data is available
889
+ /* @__PURE__ */ jsxs3("div", { children: [
890
+ /* @__PURE__ */ jsx4(
891
+ "div",
892
+ {
893
+ style: {
894
+ minHeight: "40px",
895
+ display: "flex",
896
+ alignItems: "center",
897
+ justifyContent: "center"
898
+ },
899
+ children: /* @__PURE__ */ jsx4(Spinner, { size: "md" })
900
+ }
901
+ ),
902
+ /* @__PURE__ */ jsx4(
903
+ "button",
904
+ {
905
+ type: "submit",
906
+ disabled: true,
907
+ className: buttonClassName,
908
+ "aria-busy": "false",
909
+ "aria-disabled": "true",
910
+ children: submitButtonText
911
+ }
912
+ )
913
+ ] })
914
+ ) });
915
+ };
916
+
917
+ // src/components/PlanBadge.tsx
918
+ import { useState as useState5, useEffect as useEffect3, useRef as useRef4 } from "react";
919
+ import { Fragment as Fragment2, jsx as jsx5 } from "react/jsx-runtime";
920
+ var PlanBadge = ({
921
+ children,
922
+ as: Component = "div",
923
+ className
924
+ }) => {
925
+ const { purchases, loading, hasPaidPurchase, activePurchase } = usePurchase();
926
+ const [displayPlan, setDisplayPlan] = useState5(null);
927
+ const [hasLoadedOnce, setHasLoadedOnce] = useState5(false);
928
+ const lastPlanRef = useRef4(null);
929
+ const lastLoadingRef = useRef4(true);
930
+ const previousPurchasesRef = useRef4(purchases);
931
+ const currentPlanName = activePurchase?.planName || null;
932
+ const effectivePlanName = currentPlanName;
933
+ useEffect3(() => {
934
+ if (!loading && !hasLoadedOnce) {
935
+ setHasLoadedOnce(true);
936
+ }
937
+ lastLoadingRef.current = loading;
938
+ }, [loading, hasLoadedOnce]);
939
+ useEffect3(() => {
940
+ const previousPurchases = previousPurchasesRef.current;
941
+ if (previousPurchases !== purchases) {
942
+ if (loading) {
943
+ setHasLoadedOnce(false);
944
+ }
945
+ setDisplayPlan(null);
946
+ lastPlanRef.current = null;
947
+ previousPurchasesRef.current = purchases;
948
+ }
949
+ }, [purchases, loading]);
950
+ useEffect3(() => {
951
+ const currentPlan = effectivePlanName;
952
+ const previousPlan = lastPlanRef.current;
953
+ if (currentPlan !== previousPlan) {
954
+ if (currentPlan !== null) {
955
+ lastPlanRef.current = currentPlan;
956
+ setDisplayPlan(currentPlan);
957
+ } else {
958
+ lastPlanRef.current = null;
959
+ setDisplayPlan(null);
960
+ }
961
+ } else if (currentPlan !== null && displayPlan === null) {
962
+ setDisplayPlan(currentPlan);
963
+ }
964
+ }, [effectivePlanName, displayPlan]);
965
+ const shouldShow = effectivePlanName !== null && hasLoadedOnce;
966
+ const planToDisplay = displayPlan ?? effectivePlanName;
967
+ if (children) {
968
+ return /* @__PURE__ */ jsx5(Fragment2, { children: children({ purchases, loading, displayPlan: planToDisplay, shouldShow }) });
969
+ }
970
+ if (!shouldShow) {
971
+ return null;
972
+ }
973
+ const computedClassName = typeof className === "function" ? className({ purchases }) : className;
974
+ return /* @__PURE__ */ jsx5(
975
+ Component,
976
+ {
977
+ className: computedClassName,
978
+ "data-loading": loading,
979
+ "data-has-purchase": !!activePurchase,
980
+ "data-has-paid-purchase": hasPaidPurchase,
981
+ role: "status",
982
+ "aria-live": "polite",
983
+ "aria-busy": loading,
984
+ "aria-label": `Current plan: ${planToDisplay}`,
985
+ children: planToDisplay
986
+ }
987
+ );
988
+ };
989
+
990
+ // src/components/PurchaseGate.tsx
991
+ import { Fragment as Fragment3, jsx as jsx6 } from "react/jsx-runtime";
992
+ var PurchaseGate = ({ requirePlan, requireProduct, children }) => {
993
+ const { purchases, loading, hasPlan } = usePurchase();
994
+ const hasAccess = requirePlan ? hasPlan(requirePlan) : requireProduct ? purchases.some((p) => p.status === "active" && (p.productName === requireProduct || p.productReference === requireProduct)) : purchases.some((p) => p.status === "active");
995
+ return /* @__PURE__ */ jsx6(Fragment3, { children: children({
996
+ hasAccess,
997
+ purchases,
998
+ loading
999
+ }) });
1000
+ };
1001
+
1002
+ // src/components/PlanSelector.tsx
1003
+ import { useCallback as useCallback5, useMemo as useMemo4 } from "react";
1004
+
1005
+ // src/hooks/usePlans.ts
1006
+ import { useState as useState6, useEffect as useEffect4, useCallback as useCallback4, useMemo as useMemo3, useRef as useRef5 } from "react";
1007
+ var plansCache = /* @__PURE__ */ new Map();
1008
+ var CACHE_DURATION2 = 5 * 60 * 1e3;
1009
+ function usePlans(options) {
1010
+ const { fetcher, productRef, filter, sortBy, autoSelectFirstPaid = false } = options;
1011
+ const [plans, setPlans] = useState6([]);
1012
+ const [loading, setLoading] = useState6(true);
1013
+ const [error, setError] = useState6(null);
1014
+ const [selectedPlanIndex, setSelectedPlanIndex] = useState6(0);
1015
+ const fetcherRef = useRef5(fetcher);
1016
+ const filterRef = useRef5(filter);
1017
+ const sortByRef = useRef5(sortBy);
1018
+ const autoSelectFirstPaidRef = useRef5(autoSelectFirstPaid);
1019
+ useEffect4(() => {
1020
+ fetcherRef.current = fetcher;
1021
+ }, [fetcher]);
1022
+ useEffect4(() => {
1023
+ filterRef.current = filter;
1024
+ }, [filter]);
1025
+ useEffect4(() => {
1026
+ sortByRef.current = sortBy;
1027
+ }, [sortBy]);
1028
+ useEffect4(() => {
1029
+ autoSelectFirstPaidRef.current = autoSelectFirstPaid;
1030
+ }, [autoSelectFirstPaid]);
1031
+ const fetchPlans = useCallback4(
1032
+ async (force = false) => {
1033
+ if (!productRef) {
1034
+ setError(new Error("Product reference not configured"));
1035
+ setLoading(false);
1036
+ return;
1037
+ }
1038
+ const cached = plansCache.get(productRef);
1039
+ const now = Date.now();
1040
+ if (!force && cached && now - cached.timestamp < CACHE_DURATION2) {
1041
+ const cachedPlans = cached.plans;
1042
+ let processedPlans = filterRef.current ? cachedPlans.filter(filterRef.current) : cachedPlans;
1043
+ if (sortByRef.current) {
1044
+ processedPlans = [...processedPlans].sort(sortByRef.current);
1045
+ }
1046
+ setPlans(processedPlans);
1047
+ setLoading(false);
1048
+ setError(null);
1049
+ if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
1050
+ const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
1051
+ setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
1052
+ }
1053
+ return;
1054
+ }
1055
+ if (cached?.promise) {
1056
+ try {
1057
+ setLoading(true);
1058
+ const fetchedPlans = await cached.promise;
1059
+ let processedPlans = filterRef.current ? fetchedPlans.filter(filterRef.current) : fetchedPlans;
1060
+ if (sortByRef.current) {
1061
+ processedPlans = [...processedPlans].sort(sortByRef.current);
1062
+ }
1063
+ setPlans(processedPlans);
1064
+ setError(null);
1065
+ if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
1066
+ const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
1067
+ setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
1068
+ }
1069
+ } catch (err) {
1070
+ setError(err instanceof Error ? err : new Error("Failed to load plans"));
1071
+ } finally {
1072
+ setLoading(false);
1073
+ }
1074
+ return;
1075
+ }
1076
+ try {
1077
+ setLoading(true);
1078
+ setError(null);
1079
+ const fetchPromise = fetcherRef.current(productRef);
1080
+ plansCache.set(productRef, {
1081
+ plans: [],
1082
+ timestamp: now,
1083
+ promise: fetchPromise
1084
+ });
1085
+ const fetchedPlans = await fetchPromise;
1086
+ plansCache.set(productRef, {
1087
+ plans: fetchedPlans,
1088
+ timestamp: now,
1089
+ promise: null
1090
+ });
1091
+ let processedPlans = filterRef.current ? fetchedPlans.filter(filterRef.current) : fetchedPlans;
1092
+ if (sortByRef.current) {
1093
+ processedPlans = [...processedPlans].sort(sortByRef.current);
1094
+ }
1095
+ setPlans(processedPlans);
1096
+ if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
1097
+ const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
1098
+ setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
1099
+ }
1100
+ } catch (err) {
1101
+ plansCache.delete(productRef);
1102
+ setError(err instanceof Error ? err : new Error("Failed to load plans"));
1103
+ } finally {
1104
+ setLoading(false);
1105
+ }
1106
+ },
1107
+ [productRef]
1108
+ );
1109
+ useEffect4(() => {
1110
+ fetchPlans();
1111
+ }, [fetchPlans]);
1112
+ const selectedPlan = useMemo3(() => {
1113
+ return plans[selectedPlanIndex] || null;
1114
+ }, [plans, selectedPlanIndex]);
1115
+ const selectPlan = useCallback4(
1116
+ (planRef) => {
1117
+ const index = plans.findIndex((p) => p.reference === planRef);
1118
+ if (index >= 0) {
1119
+ setSelectedPlanIndex(index);
1120
+ }
1121
+ },
1122
+ [plans]
1123
+ );
1124
+ return {
1125
+ plans,
1126
+ loading,
1127
+ error,
1128
+ selectedPlanIndex,
1129
+ selectedPlan,
1130
+ setSelectedPlanIndex,
1131
+ selectPlan,
1132
+ refetch: () => fetchPlans(true)
1133
+ // Force refetch
1134
+ };
1135
+ }
1136
+
1137
+ // src/components/PlanSelector.tsx
1138
+ import { Fragment as Fragment4, jsx as jsx7 } from "react/jsx-runtime";
1139
+ var PlanSelector = ({
1140
+ productRef,
1141
+ fetcher,
1142
+ filter,
1143
+ sortBy,
1144
+ autoSelectFirstPaid,
1145
+ children
1146
+ }) => {
1147
+ const { purchases } = usePurchase();
1148
+ const plansHook = usePlans({
1149
+ productRef,
1150
+ fetcher,
1151
+ filter,
1152
+ sortBy,
1153
+ autoSelectFirstPaid
1154
+ });
1155
+ const { plans } = plansHook;
1156
+ const isPaidPlan = useCallback5(
1157
+ (planName) => {
1158
+ const plan = plans.find((p) => p.name === planName);
1159
+ return plan ? (plan.price ?? 0) > 0 && !plan.isFreeTier : true;
1160
+ },
1161
+ [plans]
1162
+ );
1163
+ const activePurchase = useMemo4(() => {
1164
+ const activePurchases = purchases.filter((p) => p.status === "active");
1165
+ return activePurchases.sort(
1166
+ (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
1167
+ )[0] || null;
1168
+ }, [purchases]);
1169
+ const isCurrentPlan = useCallback5(
1170
+ (planName) => {
1171
+ return activePurchase?.planName === planName;
1172
+ },
1173
+ [activePurchase]
1174
+ );
1175
+ return /* @__PURE__ */ jsx7(Fragment4, { children: children({
1176
+ ...plansHook,
1177
+ purchases,
1178
+ isPaidPlan,
1179
+ isCurrentPlan
1180
+ }) });
1181
+ };
1182
+
1183
+ // src/hooks/usePurchaseStatus.ts
1184
+ import { useMemo as useMemo5, useCallback as useCallback6 } from "react";
1185
+ function usePurchaseStatus() {
1186
+ const { purchases } = usePurchase();
1187
+ const isPaidPurchase2 = useCallback6((p) => {
1188
+ return (p.amount ?? 0) > 0;
1189
+ }, []);
1190
+ const purchaseData = useMemo5(() => {
1191
+ const cancelledPaidPurchases = purchases.filter((p) => {
1192
+ return p.status === "active" && p.cancelledAt && isPaidPurchase2(p);
1193
+ });
1194
+ const cancelledPurchase = cancelledPaidPurchases.sort(
1195
+ (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
1196
+ )[0] || null;
1197
+ const shouldShowCancelledNotice = !!cancelledPurchase;
1198
+ return {
1199
+ cancelledPurchase,
1200
+ shouldShowCancelledNotice
1201
+ };
1202
+ }, [purchases, isPaidPurchase2]);
1203
+ const formatDate = useCallback6((dateString) => {
1204
+ if (!dateString) return null;
1205
+ return new Date(dateString).toLocaleDateString("en-US", {
1206
+ year: "numeric",
1207
+ month: "long",
1208
+ day: "numeric"
1209
+ });
1210
+ }, []);
1211
+ const getDaysUntilExpiration = useCallback6((endDate) => {
1212
+ if (!endDate) return null;
1213
+ const now = /* @__PURE__ */ new Date();
1214
+ const expiration = new Date(endDate);
1215
+ const diffTime = expiration.getTime() - now.getTime();
1216
+ const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
1217
+ return diffDays > 0 ? diffDays : 0;
1218
+ }, []);
1219
+ return {
1220
+ cancelledPurchase: purchaseData.cancelledPurchase,
1221
+ shouldShowCancelledNotice: purchaseData.shouldShowCancelledNotice,
1222
+ formatDate,
1223
+ getDaysUntilExpiration
1224
+ };
1225
+ }
241
1226
  export {
242
1227
  PaymentForm,
243
- SolvaPayProvider
1228
+ PlanBadge,
1229
+ PlanSelector,
1230
+ PurchaseGate,
1231
+ SolvaPayProvider,
1232
+ Spinner,
1233
+ StripePaymentFormWrapper,
1234
+ defaultAuthAdapter,
1235
+ filterPurchases,
1236
+ getActivePurchases,
1237
+ getCancelledPurchasesWithEndDate,
1238
+ getMostRecentPurchase,
1239
+ getPrimaryPurchase,
1240
+ isPaidPurchase,
1241
+ useCheckout,
1242
+ useCustomer,
1243
+ usePlans,
1244
+ usePurchase,
1245
+ usePurchaseStatus,
1246
+ useSolvaPay
244
1247
  };