@tagadapay/plugin-sdk 2.4.16 → 2.4.18

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.
@@ -1,7 +1,11 @@
1
1
  import { Customer } from '../types';
2
- export declare function useCustomer(): {
2
+ export interface UseCustomerOptions {
3
+ autoFetch?: boolean;
4
+ }
5
+ export declare function useCustomer({ autoFetch }: UseCustomerOptions): {
3
6
  customer: Customer | null;
4
7
  isAuthenticated: boolean;
5
8
  isLoading: boolean;
6
9
  isAnonymous: boolean;
10
+ refreshSession: (token?: string) => Promise<void>;
7
11
  };
@@ -3,12 +3,13 @@
3
3
  * useCustomer - Hook to access current customer data
4
4
  */
5
5
  import { useTagadaContext } from '../providers/TagadaProvider';
6
- export function useCustomer() {
7
- const { customer, isLoading } = useTagadaContext();
6
+ export function useCustomer({ autoFetch = false }) {
7
+ const { customer, isLoading, refreshSession } = useTagadaContext();
8
8
  return {
9
9
  customer,
10
10
  isAuthenticated: customer?.isAuthenticated || false,
11
11
  isLoading,
12
12
  isAnonymous: customer?.role === 'anonymous',
13
+ refreshSession,
13
14
  };
14
15
  }
@@ -0,0 +1,6 @@
1
+ export interface UseSessionRefreshResult {
2
+ refreshSession: (token?: string) => Promise<void>;
3
+ isLoading: boolean;
4
+ isSessionInitialized: boolean;
5
+ }
6
+ export declare function useSessionRefresh(): UseSessionRefreshResult;
@@ -0,0 +1,16 @@
1
+ 'use client';
2
+ /**
3
+ * useSessionRefresh - Hook to refresh the current session
4
+ *
5
+ * This hook provides a convenient way to refresh the current session,
6
+ * which will create a new anonymous token and reinitialize the session.
7
+ */
8
+ import { useTagadaContext } from '../providers/TagadaProvider';
9
+ export function useSessionRefresh() {
10
+ const { refreshSession, isLoading, isSessionInitialized } = useTagadaContext();
11
+ return {
12
+ refreshSession,
13
+ isLoading,
14
+ isSessionInitialized,
15
+ };
16
+ }
@@ -2,10 +2,10 @@
2
2
  * TagadaProvider - Main provider component for the Tagada Pay React SDK
3
3
  */
4
4
  import { ReactNode } from 'react';
5
- import { Customer, Session, AuthState, Locale, Currency, Store, Environment, EnvironmentConfig } from '../types';
6
- import { ApiService } from '../services/apiService';
7
5
  import { PluginConfig } from '../hooks/usePluginConfig';
8
- import { formatMoney, getCurrencyInfo, moneyStringOrNumberToMinorUnits, minorUnitsToMajorUnits, formatMoneyWithoutSymbol, convertCurrency, formatSimpleMoney } from '../utils/money';
6
+ import { ApiService } from '../services/apiService';
7
+ import { AuthState, Currency, Customer, Environment, EnvironmentConfig, Locale, Session, Store } from '../types';
8
+ import { convertCurrency, formatMoney, formatMoneyWithoutSymbol, formatSimpleMoney, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits } from '../utils/money';
9
9
  interface TagadaContextValue {
10
10
  auth: AuthState;
11
11
  session: Session | null;
@@ -29,6 +29,7 @@ interface TagadaContextValue {
29
29
  lastUpdated: Date | null;
30
30
  };
31
31
  updateCheckoutDebugData: (data: any, error?: Error | null, isLoading?: boolean) => void;
32
+ refreshSession: (token?: string) => Promise<void>;
32
33
  refreshCoordinator: {
33
34
  registerCheckoutRefresh: (refreshFn: () => Promise<void>) => void;
34
35
  registerOrderBumpRefresh: (refreshFn: () => Promise<void>) => void;
@@ -3,15 +3,15 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
3
3
  /**
4
4
  * TagadaProvider - Main provider component for the Tagada Pay React SDK
5
5
  */
6
- import { createContext, useContext, useState, useEffect, useRef, useCallback, useMemo, } from 'react';
7
- import { getEnvironmentConfig, detectEnvironment } from '../config/environment';
8
- import { ApiService } from '../services/apiService';
9
- import { setClientToken, getClientToken, clearClientToken } from '../utils/tokenStorage';
10
- import { decodeJWTClient, isTokenExpired } from '../utils/jwtDecoder';
11
- import { collectDeviceInfo, getBrowserLocale, getUrlParams } from '../utils/deviceInfo';
6
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react';
12
7
  import DebugDrawer from '../components/DebugDrawer';
8
+ import { detectEnvironment, getEnvironmentConfig } from '../config/environment';
13
9
  import { loadPluginConfig } from '../hooks/usePluginConfig';
14
- import { formatMoney, getCurrencyInfo, moneyStringOrNumberToMinorUnits, minorUnitsToMajorUnits, formatMoneyWithoutSymbol, convertCurrency, formatSimpleMoney, } from '../utils/money';
10
+ import { ApiService } from '../services/apiService';
11
+ import { collectDeviceInfo, getBrowserLocale, getUrlParams } from '../utils/deviceInfo';
12
+ import { decodeJWTClient, isTokenExpired } from '../utils/jwtDecoder';
13
+ import { convertCurrency, formatMoney, formatMoneyWithoutSymbol, formatSimpleMoney, getCurrencyInfo, minorUnitsToMajorUnits, moneyStringOrNumberToMinorUnits, } from '../utils/money';
14
+ import { clearClientToken, getClientToken, setClientToken } from '../utils/tokenStorage';
15
15
  // Professional, subtle loading component for initialization
16
16
  const InitializationLoader = () => (_jsxs("div", { style: {
17
17
  position: 'fixed',
@@ -271,6 +271,7 @@ localConfig, blockUntilSessionReady = false, // Default to new non-blocking beha
271
271
  }
272
272
  }
273
273
  // Update customer data if available
274
+ console.log('RESPONSE CUSTOMER', response.customer);
274
275
  if (response.customer) {
275
276
  setCustomer(response.customer);
276
277
  if (finalDebugMode) {
@@ -422,6 +423,50 @@ localConfig, blockUntilSessionReady = false, // Default to new non-blocking beha
422
423
  session,
423
424
  });
424
425
  }, [customer, session]);
426
+ // Session refresh functionality
427
+ const refreshSession = useCallback(async (providedToken) => {
428
+ if (!storeId) {
429
+ console.warn('[SDK] Cannot refresh session: No store ID available');
430
+ return;
431
+ }
432
+ console.log('[SDK] 🔄 Refreshing session...', providedToken ? 'with provided token' : 'with new anonymous token');
433
+ try {
434
+ // Clear existing token and session data
435
+ clearClientToken();
436
+ setToken(null);
437
+ setSession(null);
438
+ setCustomer(null);
439
+ setStore(null);
440
+ setIsSessionInitialized(false);
441
+ setHasAttemptedAnonymousToken(false);
442
+ // Reset initialization flag to allow re-initialization
443
+ isInitializing.current = false;
444
+ if (providedToken) {
445
+ // Use the provided token
446
+ console.log('[SDK] Using provided token for session refresh');
447
+ // Validate the token first
448
+ const decodedSession = decodeJWTClient(providedToken);
449
+ if (!decodedSession) {
450
+ throw new Error('Invalid token provided');
451
+ }
452
+ // Set the provided token
453
+ setToken(providedToken);
454
+ setClientToken(providedToken);
455
+ apiService.updateToken(providedToken);
456
+ // Initialize session with the provided token
457
+ await initializeSession(decodedSession);
458
+ }
459
+ else {
460
+ // Create new anonymous token
461
+ await createAnonymousToken(storeId);
462
+ }
463
+ console.log('[SDK] ✅ Session refreshed successfully');
464
+ }
465
+ catch (error) {
466
+ console.error('[SDK] ❌ Failed to refresh session:', error);
467
+ throw error;
468
+ }
469
+ }, [storeId, createAnonymousToken, initializeSession, apiService]);
425
470
  // Refresh coordinator for bidirectional hook communication
426
471
  const checkoutRefreshRef = useRef(null);
427
472
  const orderBumpRefreshRef = useRef(null);
@@ -493,6 +538,7 @@ localConfig, blockUntilSessionReady = false, // Default to new non-blocking beha
493
538
  lastUpdated: new Date(),
494
539
  });
495
540
  },
541
+ refreshSession,
496
542
  refreshCoordinator,
497
543
  money: {
498
544
  formatMoney,
@@ -519,6 +565,7 @@ localConfig, blockUntilSessionReady = false, // Default to new non-blocking beha
519
565
  pluginConfig,
520
566
  configLoading,
521
567
  debugCheckout,
568
+ refreshSession,
522
569
  refreshCoordinator,
523
570
  ]);
524
571
  // Determine if we should show loading
@@ -526,8 +573,8 @@ localConfig, blockUntilSessionReady = false, // Default to new non-blocking beha
526
573
  // Phase 3 (session initialization) is optional/non-blocking by default
527
574
  const shouldShowLoading = configLoading || (!storeId && configLoading);
528
575
  const canRenderChildren = blockUntilSessionReady
529
- ? (!configLoading && storeId && isInitialized) // Old behavior: wait for all phases
530
- : (!configLoading && storeId); // New behavior: render after phases 1 & 2
576
+ ? !configLoading && storeId && isInitialized // Old behavior: wait for all phases
577
+ : !configLoading && storeId; // New behavior: render after phases 1 & 2
531
578
  return (_jsxs(TagadaContext.Provider, { value: contextValue, children: [shouldShowLoading && _jsx(InitializationLoader, {}), finalDebugMode && canRenderChildren && (_jsxs(_Fragment, { children: [_jsx("button", { onClick: () => setIsDebugDrawerOpen(true), style: {
532
579
  position: 'fixed',
533
580
  bottom: '16px',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tagadapay/plugin-sdk",
3
- "version": "2.4.16",
3
+ "version": "2.4.18",
4
4
  "description": "Modern React SDK for building Tagada Pay plugins",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",