@tagadapay/plugin-sdk 3.0.2 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/build-cdn.js +113 -0
  2. package/dist/config/basisTheory.d.ts +26 -0
  3. package/dist/config/basisTheory.js +29 -0
  4. package/dist/external-tracker.js +4947 -0
  5. package/dist/external-tracker.min.js +11 -0
  6. package/dist/external-tracker.min.js.map +7 -0
  7. package/dist/react/config/payment.d.ts +8 -8
  8. package/dist/react/config/payment.js +17 -21
  9. package/dist/react/hooks/useApplePay.js +1 -1
  10. package/dist/react/hooks/usePayment.js +1 -3
  11. package/dist/react/hooks/useThreeds.js +2 -2
  12. package/dist/v2/core/client.d.ts +31 -3
  13. package/dist/v2/core/client.js +234 -9
  14. package/dist/v2/core/config/environment.d.ts +16 -3
  15. package/dist/v2/core/config/environment.js +72 -3
  16. package/dist/v2/core/funnelClient.d.ts +4 -0
  17. package/dist/v2/core/funnelClient.js +106 -4
  18. package/dist/v2/core/resources/funnel.d.ts +22 -0
  19. package/dist/v2/core/resources/offers.d.ts +64 -3
  20. package/dist/v2/core/resources/offers.js +112 -10
  21. package/dist/v2/core/resources/postPurchases.js +4 -1
  22. package/dist/v2/core/utils/configHotReload.d.ts +39 -0
  23. package/dist/v2/core/utils/configHotReload.js +75 -0
  24. package/dist/v2/core/utils/eventBus.d.ts +11 -0
  25. package/dist/v2/core/utils/eventBus.js +34 -0
  26. package/dist/v2/core/utils/pluginConfig.d.ts +14 -5
  27. package/dist/v2/core/utils/pluginConfig.js +74 -59
  28. package/dist/v2/core/utils/previewMode.d.ts +114 -0
  29. package/dist/v2/core/utils/previewMode.js +379 -0
  30. package/dist/v2/core/utils/sessionStorage.d.ts +5 -0
  31. package/dist/v2/core/utils/sessionStorage.js +22 -0
  32. package/dist/v2/index.d.ts +4 -1
  33. package/dist/v2/index.js +3 -1
  34. package/dist/v2/react/hooks/useOfferQuery.js +50 -17
  35. package/dist/v2/react/hooks/usePaymentQuery.js +1 -3
  36. package/dist/v2/react/hooks/usePreviewOffer.d.ts +84 -0
  37. package/dist/v2/react/hooks/usePreviewOffer.js +290 -0
  38. package/dist/v2/react/hooks/useThreeds.js +2 -2
  39. package/dist/v2/react/index.d.ts +2 -0
  40. package/dist/v2/react/index.js +1 -0
  41. package/dist/v2/react/providers/TagadaProvider.d.ts +1 -2
  42. package/dist/v2/react/providers/TagadaProvider.js +51 -34
  43. package/dist/v2/standalone/external-tracker.d.ts +119 -0
  44. package/dist/v2/standalone/external-tracker.js +260 -0
  45. package/dist/v2/standalone/index.d.ts +2 -0
  46. package/dist/v2/standalone/index.js +6 -0
  47. package/package.json +11 -3
  48. package/dist/v2/react/hooks/useOffersQuery.d.ts +0 -12
  49. package/dist/v2/react/hooks/useOffersQuery.js +0 -404
@@ -1,404 +0,0 @@
1
- /**
2
- * Offers Hook using TanStack Query
3
- * Handles offers with automatic caching
4
- */
5
- import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
6
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
- import { OffersResource } from '../../core/resources/offers';
8
- import { useTagadaContext } from '../providers/TagadaProvider';
9
- import { getGlobalApiClient } from './useApiQuery';
10
- import { usePluginConfig } from './usePluginConfig';
11
- export function useOffersQuery(options = {}) {
12
- const { offerIds = [], enabled = true, returnUrl, orderId: defaultOrderId, activeOfferId, skipPreview = false } = options;
13
- const { storeId } = usePluginConfig();
14
- const { isSessionInitialized, session } = useTagadaContext();
15
- const _queryClient = useQueryClient();
16
- // Version identifier for debugging
17
- console.log('[useOffersQuery] Hook initialized - VERSION: 2.2-production-ready', {
18
- activeOfferId,
19
- skipPreview,
20
- isSessionInitialized,
21
- });
22
- // State for checkout sessions per offer (similar to postPurchases)
23
- const [checkoutSessions, setCheckoutSessions] = useState({});
24
- const [isActiveSummaryLoading, setIsActiveSummaryLoading] = useState(false);
25
- const lastPreviewedOfferRef = useRef(null);
26
- // Use ref to break dependency cycles in callbacks
27
- const checkoutSessionsRef = useRef(checkoutSessions);
28
- // Update ref on every render
29
- checkoutSessionsRef.current = checkoutSessions;
30
- // Create offers resource client
31
- const offersResource = useMemo(() => {
32
- try {
33
- return new OffersResource(getGlobalApiClient());
34
- }
35
- catch (error) {
36
- throw new Error('Failed to initialize offers resource: ' + (error instanceof Error ? error.message : 'Unknown error'));
37
- }
38
- }, []);
39
- // Helper function for fetching order summary (similar to postPurchases)
40
- const fetchOrderSummary = useCallback(async (offerId, sessionId) => {
41
- if (!isSessionInitialized)
42
- return null;
43
- try {
44
- // Set updating state
45
- setCheckoutSessions(prev => ({
46
- ...prev,
47
- [offerId]: {
48
- ...prev[offerId],
49
- isUpdatingSummary: true,
50
- }
51
- }));
52
- const summaryResult = await offersResource.getOrderSummary(sessionId, true);
53
- if (summaryResult) {
54
- // Sort items by productId to ensure consistent order
55
- const sortedItems = [...summaryResult.items].sort((a, b) => a.productId.localeCompare(b.productId));
56
- const orderSummary = {
57
- ...summaryResult,
58
- items: sortedItems,
59
- };
60
- // Initialize selected variants based on the summary
61
- const initialVariants = {};
62
- sortedItems.forEach((item) => {
63
- if (item.productId && item.variantId) {
64
- initialVariants[item.productId] = item.variantId;
65
- }
66
- });
67
- setCheckoutSessions(prev => ({
68
- ...prev,
69
- [offerId]: {
70
- ...prev[offerId],
71
- orderSummary,
72
- selectedVariants: initialVariants,
73
- isUpdatingSummary: false,
74
- }
75
- }));
76
- return orderSummary;
77
- }
78
- return null;
79
- }
80
- catch (error) {
81
- setCheckoutSessions(prev => ({
82
- ...prev,
83
- [offerId]: {
84
- ...prev[offerId],
85
- isUpdatingSummary: false,
86
- }
87
- }));
88
- throw error;
89
- }
90
- }, [offersResource, isSessionInitialized]);
91
- // Create query key based on options
92
- const queryKey = useMemo(() => ['offers', { storeId, offerIds }], [storeId, offerIds]);
93
- // Use TanStack Query for fetching offers
94
- const { data: offers = [], isLoading, error } = useQuery({
95
- queryKey,
96
- enabled: enabled && !!storeId && isSessionInitialized,
97
- queryFn: async () => {
98
- if (!storeId) {
99
- throw new Error('Store ID not found. Make sure the TagadaProvider is properly configured.');
100
- }
101
- if (offerIds.length > 0) {
102
- // Fetch specific offers by IDs
103
- return await offersResource.getOffersByIds(storeId, offerIds);
104
- }
105
- else {
106
- // Fetch all offers for the store
107
- return await offersResource.getOffers(storeId);
108
- }
109
- },
110
- staleTime: 5 * 60 * 1000, // 5 minutes
111
- refetchOnWindowFocus: false,
112
- });
113
- const { mutateAsync: payWithCheckoutSessionAsync } = useMutation({
114
- mutationFn: async ({ checkoutSessionId, orderId }) => {
115
- return await offersResource.payWithCheckoutSession(checkoutSessionId, orderId);
116
- },
117
- onError: (_error) => {
118
- // Error handling removed
119
- },
120
- });
121
- const { mutateAsync: initCheckoutSessionAsync } = useMutation({
122
- mutationFn: async ({ offerId, orderId, customerId }) => {
123
- return await offersResource.initCheckoutSession(offerId, orderId, customerId);
124
- },
125
- onError: (_error) => {
126
- // Error handling removed
127
- },
128
- });
129
- const payWithCheckoutSession = useCallback(async (checkoutSessionId, orderId) => {
130
- return await payWithCheckoutSessionAsync({ checkoutSessionId, orderId });
131
- }, [payWithCheckoutSessionAsync]);
132
- const initCheckoutSession = useCallback(async (offerId, orderId, customerId) => {
133
- if (!isSessionInitialized) {
134
- throw new Error('Cannot initialize checkout session: CMS session is not initialized');
135
- }
136
- // Use customerId from session context if not provided
137
- const effectiveCustomerId = customerId || session?.customerId;
138
- if (!effectiveCustomerId) {
139
- throw new Error('Customer ID is required. Make sure the session is properly initialized.');
140
- }
141
- return await initCheckoutSessionAsync({
142
- offerId,
143
- orderId,
144
- customerId: effectiveCustomerId
145
- });
146
- }, [initCheckoutSessionAsync, session?.customerId, isSessionInitialized]);
147
- const payOffer = useCallback(async (offerId, orderId) => {
148
- if (!isSessionInitialized) {
149
- throw new Error('Cannot pay offer: CMS session is not initialized');
150
- }
151
- const effectiveOrderId = orderId || defaultOrderId;
152
- const effectiveCustomerId = session?.customerId;
153
- if (!effectiveOrderId) {
154
- throw new Error('Order ID is required for payment. Please provide it in the hook options or the function call.');
155
- }
156
- if (!effectiveCustomerId) {
157
- throw new Error('Customer ID is required. Make sure the session is properly initialized.');
158
- }
159
- // 1. Init session
160
- const { checkoutSessionId } = await initCheckoutSession(offerId, effectiveOrderId, effectiveCustomerId);
161
- // 2. Pay
162
- await payWithCheckoutSession(checkoutSessionId, effectiveOrderId);
163
- }, [initCheckoutSession, payWithCheckoutSession, defaultOrderId, session?.customerId, isSessionInitialized]);
164
- const preview = useCallback(async (offerId) => {
165
- console.log('[useOffersQuery] preview() called for offer:', offerId);
166
- if (!isSessionInitialized) {
167
- console.log('[useOffersQuery] preview() - session not initialized, returning null');
168
- // Return null silently to avoid errors during auto-initialization phases
169
- return null;
170
- }
171
- const effectiveOrderId = defaultOrderId;
172
- const effectiveCustomerId = session?.customerId;
173
- // Use ref to check current state without creating dependency
174
- const currentSessions = checkoutSessionsRef.current;
175
- // If we already have a summary in state, return it
176
- if (currentSessions[offerId]?.orderSummary) {
177
- console.log('[useOffersQuery] preview() - using cached summary for offer:', offerId);
178
- return currentSessions[offerId].orderSummary;
179
- }
180
- // Prevent duplicate initialization if already has a session and is updating
181
- if (currentSessions[offerId]?.checkoutSessionId && currentSessions[offerId]?.isUpdatingSummary) {
182
- console.log('[useOffersQuery] preview() - already updating, skipping for offer:', offerId);
183
- return null;
184
- }
185
- // If we don't have orderId, fallback to static summary from offer object
186
- // as we can't initialize a checkout session properly without orderId (for upsells)
187
- if (!effectiveOrderId || !effectiveCustomerId) {
188
- const offer = offers.find(o => o.id === offerId);
189
- return offer?.summaries?.[0] || null;
190
- }
191
- try {
192
- // If we already have a session ID, reuse it instead of creating a new one
193
- let sessionId = currentSessions[offerId]?.checkoutSessionId;
194
- if (!sessionId) {
195
- const { checkoutSessionId } = await initCheckoutSession(offerId, effectiveOrderId, effectiveCustomerId);
196
- sessionId = checkoutSessionId;
197
- // Update state with session ID
198
- setCheckoutSessions(prev => ({
199
- ...prev,
200
- [offerId]: {
201
- checkoutSessionId: sessionId,
202
- orderSummary: null,
203
- selectedVariants: {},
204
- loadingVariants: {},
205
- isUpdatingSummary: false,
206
- }
207
- }));
208
- }
209
- // Fetch and return summary
210
- return await fetchOrderSummary(offerId, sessionId);
211
- }
212
- catch (e) {
213
- console.error("Failed to preview offer", e);
214
- return null;
215
- }
216
- }, [offers, defaultOrderId, session?.customerId, initCheckoutSession, fetchOrderSummary, isSessionInitialized]); // Removed checkoutSessions dependency
217
- // Auto-preview effect for activeOfferId
218
- useEffect(() => {
219
- console.log('[useOffersQuery v2.2] Auto-preview effect triggered:', {
220
- activeOfferId,
221
- skipPreview,
222
- isSessionInitialized,
223
- lastPreviewed: lastPreviewedOfferRef.current,
224
- });
225
- if (!activeOfferId || skipPreview || !isSessionInitialized) {
226
- console.log('[useOffersQuery] Skipping auto-preview - conditions not met');
227
- setIsActiveSummaryLoading(false); // Reset loading state if conditions not met
228
- // Reset the ref when conditions are not met
229
- if (!activeOfferId) {
230
- lastPreviewedOfferRef.current = null;
231
- }
232
- return;
233
- }
234
- // Skip if we've already previewed this exact offer
235
- if (lastPreviewedOfferRef.current === activeOfferId) {
236
- console.log('[useOffersQuery] Skipping auto-preview - already previewed:', activeOfferId);
237
- setIsActiveSummaryLoading(false); // Ensure loading is false
238
- return;
239
- }
240
- console.log('[useOffersQuery] Starting auto-preview for offer:', activeOfferId);
241
- let isMounted = true;
242
- setIsActiveSummaryLoading(true); // Set loading immediately
243
- // Debounce the preview call
244
- const timer = setTimeout(() => {
245
- if (!isMounted) {
246
- console.log('[useOffersQuery] Component unmounted before preview call');
247
- return;
248
- }
249
- console.log('[useOffersQuery] Calling preview for offer:', activeOfferId);
250
- preview(activeOfferId)
251
- .then(() => {
252
- if (isMounted) {
253
- console.log('[useOffersQuery] Preview successful for offer:', activeOfferId);
254
- lastPreviewedOfferRef.current = activeOfferId; // Mark as previewed on success
255
- }
256
- })
257
- .catch(err => {
258
- console.error('[useOffersQuery] Failed to auto-preview offer:', activeOfferId, err);
259
- // Don't mark as previewed on error, to avoid infinite retry loop
260
- })
261
- .finally(() => {
262
- if (isMounted) {
263
- console.log('[useOffersQuery] Preview finished for offer:', activeOfferId);
264
- setIsActiveSummaryLoading(false);
265
- }
266
- });
267
- }, 50);
268
- return () => {
269
- console.log('[useOffersQuery] Cleaning up auto-preview effect for offer:', activeOfferId);
270
- isMounted = false;
271
- clearTimeout(timer);
272
- setIsActiveSummaryLoading(false); // Reset loading on unmount/cleanup
273
- };
274
- }, [activeOfferId, skipPreview, isSessionInitialized]); // FIXED: Removed 'preview' from dependencies to prevent infinite loop
275
- const activeSummary = useMemo(() => {
276
- if (!activeOfferId)
277
- return null;
278
- // Return dynamic summary if available, otherwise fallback to static summary
279
- return checkoutSessions[activeOfferId]?.orderSummary || offers.find(o => o.id === activeOfferId)?.summaries?.[0] || null;
280
- }, [activeOfferId, checkoutSessions, offers]);
281
- const getAvailableVariants = useCallback((offerId, productId) => {
282
- const sessionState = checkoutSessions[offerId]; // This hook needs to react to state changes
283
- if (!sessionState?.orderSummary?.options?.[productId])
284
- return [];
285
- return sessionState.orderSummary.options[productId].map((variant) => ({
286
- variantId: variant.id,
287
- variantName: variant.name,
288
- variantSku: variant.sku,
289
- variantDefault: variant.default,
290
- variantExternalId: variant.externalVariantId,
291
- priceId: variant.prices[0]?.id,
292
- currencyOptions: variant.prices[0]?.currencyOptions,
293
- }));
294
- }, [checkoutSessions]);
295
- const isLoadingVariants = useCallback((offerId, productId) => {
296
- return checkoutSessions[offerId]?.loadingVariants?.[productId] ?? false;
297
- }, [checkoutSessions]);
298
- const selectVariant = useCallback(async (offerId, productId, variantId) => {
299
- if (!isSessionInitialized) {
300
- throw new Error('Cannot select variant: CMS session is not initialized');
301
- }
302
- // Use ref for initial check to avoid dependency but we might need latest state for logic
303
- // Actually for actions it's better to use ref or just dependency if action is not called in useEffect
304
- const currentSessions = checkoutSessionsRef.current;
305
- const sessionState = currentSessions[offerId];
306
- if (!sessionState?.checkoutSessionId || !sessionState.orderSummary) {
307
- throw new Error('Checkout session not initialized for this offer');
308
- }
309
- const sessionId = sessionState.checkoutSessionId;
310
- // Set loading state for this specific variant
311
- setCheckoutSessions(prev => ({
312
- ...prev,
313
- [offerId]: {
314
- ...prev[offerId],
315
- loadingVariants: {
316
- ...prev[offerId].loadingVariants,
317
- [productId]: true,
318
- }
319
- }
320
- }));
321
- try {
322
- // We need to use the state from the ref to ensure we have the latest data without causing infinite loops
323
- // if selectVariant was in a dependency array that triggered effects
324
- const sessionState = checkoutSessionsRef.current[offerId];
325
- if (!sessionState?.orderSummary?.options?.[productId]) {
326
- throw new Error('No variants available for this product');
327
- }
328
- const availableVariants = sessionState.orderSummary.options[productId].map((variant) => ({
329
- variantId: variant.id,
330
- variantName: variant.name,
331
- variantSku: variant.sku,
332
- variantDefault: variant.default,
333
- variantExternalId: variant.externalVariantId,
334
- priceId: variant.prices[0]?.id,
335
- currencyOptions: variant.prices[0]?.currencyOptions,
336
- }));
337
- const selectedVariant = availableVariants.find(v => v.variantId === variantId);
338
- if (!selectedVariant) {
339
- throw new Error('Selected variant not found');
340
- }
341
- // Find the current item to get its quantity
342
- const currentItem = sessionState.orderSummary.items.find(item => item.productId === productId);
343
- if (!currentItem) {
344
- throw new Error('Current item not found');
345
- }
346
- // Update selected variants state
347
- setCheckoutSessions(prev => ({
348
- ...prev,
349
- [offerId]: {
350
- ...prev[offerId],
351
- selectedVariants: {
352
- ...prev[offerId].selectedVariants,
353
- [productId]: variantId,
354
- }
355
- }
356
- }));
357
- // Update line items on the server
358
- await offersResource.updateLineItems(sessionId, [
359
- {
360
- variantId: selectedVariant.variantId,
361
- quantity: currentItem.quantity,
362
- },
363
- ]);
364
- // Refetch order summary after successful line item update
365
- return await fetchOrderSummary(offerId, sessionId);
366
- }
367
- finally {
368
- // Clear loading state for this specific variant
369
- setCheckoutSessions(prev => ({
370
- ...prev,
371
- [offerId]: {
372
- ...prev[offerId],
373
- loadingVariants: {
374
- ...prev[offerId].loadingVariants,
375
- [productId]: false,
376
- }
377
- }
378
- }));
379
- }
380
- }, [offersResource, fetchOrderSummary, isSessionInitialized]); // Removed checkoutSessions dependency
381
- const result = {
382
- // Query data
383
- offers,
384
- isLoading,
385
- error,
386
- activeSummary,
387
- isActiveSummaryLoading,
388
- // Actions
389
- payOffer,
390
- preview,
391
- getAvailableVariants,
392
- selectVariant,
393
- isLoadingVariants,
394
- };
395
- console.log('[useOffersQuery] Returning result:', {
396
- offersCount: offers.length,
397
- isLoading,
398
- hasError: !!error,
399
- activeOfferId,
400
- hasActiveSummary: !!activeSummary,
401
- isActiveSummaryLoading,
402
- });
403
- return result;
404
- }