@tiendanube/live-state 1.0.0-beta.18 → 1.0.0-beta.19

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.
@@ -96,23 +96,23 @@ function v() {
96
96
  //#endregion
97
97
  //#region src/providers/LiveStateProvider.tsx
98
98
  var y = e(null);
99
- function b({ children: e, fetcher: t, analytics: a, onEvent: s, onLog: l, onNavigate: f, mockData: p, disabled: m = !1 }) {
100
- let h = r(() => c(l), [l]);
99
+ function b({ children: e, fetcher: t, analytics: a, onEvent: s, onLog: l, onNavigate: f, mockData: p, disabled: m = !1, cacheProvider: h }) {
100
+ let g = r(() => c(l), [l]);
101
101
  n(() => {
102
- m || (a?.amplitudeKey && u(a.amplitudeKey, h), a?.clarityProjectId && d(a.clarityProjectId, h));
102
+ m || (a?.amplitudeKey && u(a.amplitudeKey, g), a?.clarityProjectId && d(a.clarityProjectId, g));
103
103
  }, [
104
104
  a,
105
105
  m,
106
- h
106
+ g
107
107
  ]);
108
- let g = r(() => ({
108
+ let _ = r(() => ({
109
109
  fetcher: t,
110
110
  analytics: a,
111
111
  onEvent: s,
112
112
  onNavigate: f,
113
113
  mockData: p,
114
114
  disabled: m,
115
- log: h
115
+ log: g
116
116
  }), [
117
117
  t,
118
118
  a,
@@ -120,12 +120,12 @@ function b({ children: e, fetcher: t, analytics: a, onEvent: s, onLog: l, onNavi
120
120
  f,
121
121
  p,
122
122
  m,
123
- h
123
+ g
124
124
  ]);
125
125
  return /* @__PURE__ */ o(i, {
126
- value: { provider: () => /* @__PURE__ */ new Map() },
126
+ value: { provider: h ? () => h : () => /* @__PURE__ */ new Map() },
127
127
  children: /* @__PURE__ */ o(y.Provider, {
128
- value: g,
128
+ value: _,
129
129
  children: e
130
130
  })
131
131
  });
@@ -138,4 +138,4 @@ function x() {
138
138
  //#endregion
139
139
  export { _ as a, g as i, x as n, c as o, h as r, b as t };
140
140
 
141
- //# sourceMappingURL=LiveStateProvider-V3rVH59O.js.map
141
+ //# sourceMappingURL=LiveStateProvider-AFY4pRGk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"LiveStateProvider-V3rVH59O.js","names":[],"sources":["../src/utils/logger.ts","../src/utils/analytics.ts","../src/providers/LiveStateProvider.tsx"],"sourcesContent":["import type { LogLevel } from '../types';\n\n/**\n * Logger function type — matches the signature of LiveStateProviderProps.onLog.\n */\nexport type LoggerFn = (\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n) => void;\n\n/**\n * Default logger — falls back to console.* when no onLog is provided.\n * Uses console.warn for 'info' and 'warn', console.error for 'error'.\n */\nconst defaultLogger: LoggerFn = (level, message, context) => {\n const prefix = '[LiveState]';\n if (level === 'error') {\n console.error(prefix, message, ...(context ? [context] : []));\n } else {\n console.warn(prefix, message, ...(context ? [context] : []));\n }\n};\n\n/**\n * Creates a logger bound to an optional consumer-provided onLog callback.\n * When onLog is provided it is called exclusively — the default console.*\n * fallback does NOT run, giving the consumer full control over output.\n *\n * @example\n * const log = createLogger(onLog);\n * log('warn', 'Amplitude API key not provided');\n * log('error', 'Failed to fetch', { url: '/v1/live-state', status: 500 });\n */\nexport function createLogger(onLog?: LoggerFn): LoggerFn {\n return (level, message, context) => {\n if (onLog) {\n onLog(level, message, context);\n } else {\n defaultLogger(level, message, context);\n }\n };\n}\n","import * as amplitude from '@amplitude/analytics-browser';\nimport type { TrackingProperties, TrackingValue } from '../types';\nimport { createLogger, type LoggerFn } from './logger';\n\n/**\n * Isolated Amplitude instance for the lib — avoids conflicts with the\n * consumer app's own Amplitude instance when both coexist on the same page.\n */\nconst amplitudeInstance = amplitude.createInstance();\n\n/**\n * Initialize Amplitude (fail silently)\n */\nexport function initializeAmplitude(apiKey: string, log?: LoggerFn): void {\n const logger = createLogger(log);\n try {\n if (!apiKey) {\n logger('warn', 'Amplitude API key not provided');\n return;\n }\n\n amplitudeInstance.init(apiKey, {\n defaultTracking: false,\n });\n } catch (error) {\n logger('error', 'Failed to initialize Amplitude', { error });\n }\n}\n\n/**\n * Initialize Clarity (fail silently)\n */\nexport async function initializeClarity(\n projectId?: string,\n log?: LoggerFn,\n): Promise<void> {\n const logger = createLogger(log);\n try {\n // Check if Clarity is already loaded by the client\n if (getClarity()) {\n logger('info', 'Clarity already initialized by client');\n return;\n }\n\n // If client provided project ID, use it\n const finalProjectId = projectId || getClientClarityProjectId();\n\n if (!finalProjectId) {\n logger('warn', 'Clarity project ID not provided');\n return;\n }\n\n // Initialize Clarity with project ID\n const Clarity = (await import('@microsoft/clarity')).default;\n Clarity.init(finalProjectId);\n } catch (error) {\n logger('error', 'Failed to initialize Clarity', { error });\n }\n}\n\n/**\n * Try to extract Clarity project ID from client's installation\n */\nfunction getClientClarityProjectId(): string | undefined {\n try {\n // Check if Clarity script tag exists\n const clarityScript = document.querySelector('script[src*=\"clarity.ms\"]');\n if (clarityScript) {\n const src = clarityScript.getAttribute('src');\n const match = src?.match(/\\/([a-z0-9]+)$/);\n return match?.[1];\n }\n\n // Check global clarity config: shape is clarity.q = [['init', projectId, ...]]\n const projectId = getClarity()?.q?.[0]?.[1];\n if (typeof projectId === 'string') {\n return projectId;\n }\n } catch {\n // Fail silently\n }\n\n return undefined;\n}\n\n/**\n * Track event with Amplitude (fail silently)\n */\nexport function trackAmplitudeEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n amplitudeInstance.track(eventName, properties);\n } catch (error) {\n logger('error', 'Failed to track Amplitude event', { eventName, error });\n }\n}\n\n/**\n * Track event with Clarity (fail silently)\n */\nexport function trackClarityEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n const clarity = getClarity();\n if (clarity) {\n clarity('event', eventName);\n\n // Set custom tags for properties\n if (properties) {\n Object.entries(properties).forEach(([key, value]) => {\n clarity('set', key, String(value));\n });\n }\n }\n } catch (error) {\n logger('error', 'Failed to track Clarity event', { eventName, error });\n }\n}\n\n/**\n * Builds a tracking event name from prefix, page and event segments.\n * The prefix is expected to already include a trailing separator (e.g. 'nuvempago_lending_').\n * Page is optional — when absent the segment is omitted from the name.\n *\n * @example\n * buildEventName('nuvempago_lending_', 'dashboard', 'charge', 'view')\n * // → 'nuvempago_lending_dashboard_charge_view'\n *\n * buildEventName('nuvempago_lending_', undefined, 'charge', 'view')\n * // → 'nuvempago_lending_charge_view'\n */\nexport function buildEventName(\n prefix: string,\n page: string | undefined,\n context: string,\n event: string,\n): string {\n // Prefix already contains its trailing separator — join only the remaining segments\n const segments = [page, context, event].filter(Boolean);\n return `${prefix}${segments.join('_')}`;\n}\n\n/**\n * Builds a TrackingProperties object from a loose record, dropping entries\n * whose value is undefined so callers don't need to guard optional fields.\n */\nexport function buildTrackingProperties(\n source: Record<string, TrackingValue | undefined>,\n): TrackingProperties {\n return Object.fromEntries(\n Object.entries(source).filter(\n (entry): entry is [string, TrackingValue] => entry[1] !== undefined,\n ),\n );\n}\n\n/**\n * Track event with both Amplitude and Clarity (fail silently)\n */\nexport function trackEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n trackAmplitudeEvent(eventName, properties, log);\n trackClarityEvent(eventName, properties, log);\n}\n\n/**\n * Clarity command API shape — kept module-local to avoid polluting the\n * consumer's global Window type with a conflicting declaration.\n * https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-api\n */\ntype ClarityCommand =\n | 'init'\n | 'event'\n | 'set'\n | 'identify'\n | 'consent'\n | 'upgrade';\n\ntype ClarityFn = {\n (command: ClarityCommand, ...args: string[]): void;\n q?: string[][];\n};\n\n/** Access window.clarity without declaring a global augmentation */\nfunction getClarity(): ClarityFn | undefined {\n return (window as unknown as Record<string, unknown>).clarity as\n | ClarityFn\n | undefined;\n}\n","import { createContext, useContext, useEffect, useMemo } from 'react';\nimport { SWRConfig } from 'swr';\nimport type {\n LiveStateFetcher,\n AnalyticsConfig,\n TrackingProperties,\n LiveStateResponse,\n CtaConfig,\n LiveStateProviderProps,\n} from '../types';\nimport { initializeAmplitude, initializeClarity } from '../utils/analytics';\nimport { createLogger, type LoggerFn } from '../utils/logger';\n\ninterface LiveStateContextValue {\n fetcher: LiveStateFetcher;\n analytics?: AnalyticsConfig;\n onEvent?: (eventName: string, properties?: TrackingProperties) => void;\n onNavigate?: (cta: CtaConfig) => void;\n mockData?: LiveStateResponse | null;\n disabled?: boolean;\n log: LoggerFn;\n}\n\nconst LiveStateContext = createContext<LiveStateContextValue | null>(null);\n\n/**\n * LiveStateProvider\n *\n * Root-level provider that configures fetcher function and analytics.\n * Initializes Amplitude and Clarity on mount.\n *\n * The optional `onEvent` callback is fired on every tracking event before\n * sending to Amplitude/Clarity — useful for simulators and debugging tools.\n *\n * The optional `onLog` callback receives all internal lib logs — route them\n * to your APM (Datadog, Sentry, etc.) to avoid relying on console.*.\n *\n * See examples/ directory for usage examples.\n */\nexport function LiveStateProvider({\n children,\n fetcher,\n analytics,\n onEvent,\n onLog,\n onNavigate,\n mockData,\n disabled = false,\n}: LiveStateProviderProps) {\n const log = useMemo(() => createLogger(onLog), [onLog]);\n\n useEffect(() => {\n if (disabled) return;\n\n if (analytics?.amplitudeKey) {\n initializeAmplitude(analytics.amplitudeKey, log);\n }\n\n if (analytics?.clarityProjectId) {\n initializeClarity(analytics.clarityProjectId, log);\n }\n }, [analytics, disabled, log]);\n\n const contextValue = useMemo(\n () => ({ fetcher, analytics, onEvent, onNavigate, mockData, disabled, log }),\n [fetcher, analytics, onEvent, onNavigate, mockData, disabled, log],\n );\n\n return (\n <SWRConfig value={{ provider: () => new Map() }}>\n <LiveStateContext.Provider value={contextValue}>\n {children}\n </LiveStateContext.Provider>\n </SWRConfig>\n );\n}\n\n/**\n * useLiveStateContext\n *\n * Internal hook to access LiveStateContext\n */\nexport function useLiveStateContext() {\n const context = useContext(LiveStateContext);\n\n if (!context) {\n throw new Error('useLiveState must be used within LiveStateProvider');\n }\n\n return context;\n}\n"],"mappings":";;;;;AAeA,IAAM,KAA2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AC;EAAS;EAAW;EAAS;EAAY;EAAU;EAAU;EAAI,CACnE;AAED,QACE,kBAAC,GAAD;EAAW,OAAO,EAAE,gCAAgB,IAAI,KAAK,EAAE;YAC7C,kBAAC,EAAiB,UAAlB;GAA2B,OAAO;GAC/B;GACyB,CAAA;EAClB,CAAA;;AAShB,SAAgB,IAAsB;CACpC,IAAM,IAAU,EAAW,EAAiB;AAE5C,KAAI,CAAC,EACH,OAAU,MAAM,qDAAqD;AAGvE,QAAO"}
1
+ {"version":3,"file":"LiveStateProvider-AFY4pRGk.js","names":[],"sources":["../src/utils/logger.ts","../src/utils/analytics.ts","../src/providers/LiveStateProvider.tsx"],"sourcesContent":["import type { LogLevel } from '../types';\n\n/**\n * Logger function type — matches the signature of LiveStateProviderProps.onLog.\n */\nexport type LoggerFn = (\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n) => void;\n\n/**\n * Default logger — falls back to console.* when no onLog is provided.\n * Uses console.warn for 'info' and 'warn', console.error for 'error'.\n */\nconst defaultLogger: LoggerFn = (level, message, context) => {\n const prefix = '[LiveState]';\n if (level === 'error') {\n console.error(prefix, message, ...(context ? [context] : []));\n } else {\n console.warn(prefix, message, ...(context ? [context] : []));\n }\n};\n\n/**\n * Creates a logger bound to an optional consumer-provided onLog callback.\n * When onLog is provided it is called exclusively — the default console.*\n * fallback does NOT run, giving the consumer full control over output.\n *\n * @example\n * const log = createLogger(onLog);\n * log('warn', 'Amplitude API key not provided');\n * log('error', 'Failed to fetch', { url: '/v1/live-state', status: 500 });\n */\nexport function createLogger(onLog?: LoggerFn): LoggerFn {\n return (level, message, context) => {\n if (onLog) {\n onLog(level, message, context);\n } else {\n defaultLogger(level, message, context);\n }\n };\n}\n","import * as amplitude from '@amplitude/analytics-browser';\nimport type { TrackingProperties, TrackingValue } from '../types';\nimport { createLogger, type LoggerFn } from './logger';\n\n/**\n * Isolated Amplitude instance for the lib — avoids conflicts with the\n * consumer app's own Amplitude instance when both coexist on the same page.\n */\nconst amplitudeInstance = amplitude.createInstance();\n\n/**\n * Initialize Amplitude (fail silently)\n */\nexport function initializeAmplitude(apiKey: string, log?: LoggerFn): void {\n const logger = createLogger(log);\n try {\n if (!apiKey) {\n logger('warn', 'Amplitude API key not provided');\n return;\n }\n\n amplitudeInstance.init(apiKey, {\n defaultTracking: false,\n });\n } catch (error) {\n logger('error', 'Failed to initialize Amplitude', { error });\n }\n}\n\n/**\n * Initialize Clarity (fail silently)\n */\nexport async function initializeClarity(\n projectId?: string,\n log?: LoggerFn,\n): Promise<void> {\n const logger = createLogger(log);\n try {\n // Check if Clarity is already loaded by the client\n if (getClarity()) {\n logger('info', 'Clarity already initialized by client');\n return;\n }\n\n // If client provided project ID, use it\n const finalProjectId = projectId || getClientClarityProjectId();\n\n if (!finalProjectId) {\n logger('warn', 'Clarity project ID not provided');\n return;\n }\n\n // Initialize Clarity with project ID\n const Clarity = (await import('@microsoft/clarity')).default;\n Clarity.init(finalProjectId);\n } catch (error) {\n logger('error', 'Failed to initialize Clarity', { error });\n }\n}\n\n/**\n * Try to extract Clarity project ID from client's installation\n */\nfunction getClientClarityProjectId(): string | undefined {\n try {\n // Check if Clarity script tag exists\n const clarityScript = document.querySelector('script[src*=\"clarity.ms\"]');\n if (clarityScript) {\n const src = clarityScript.getAttribute('src');\n const match = src?.match(/\\/([a-z0-9]+)$/);\n return match?.[1];\n }\n\n // Check global clarity config: shape is clarity.q = [['init', projectId, ...]]\n const projectId = getClarity()?.q?.[0]?.[1];\n if (typeof projectId === 'string') {\n return projectId;\n }\n } catch {\n // Fail silently\n }\n\n return undefined;\n}\n\n/**\n * Track event with Amplitude (fail silently)\n */\nexport function trackAmplitudeEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n amplitudeInstance.track(eventName, properties);\n } catch (error) {\n logger('error', 'Failed to track Amplitude event', { eventName, error });\n }\n}\n\n/**\n * Track event with Clarity (fail silently)\n */\nexport function trackClarityEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n const clarity = getClarity();\n if (clarity) {\n clarity('event', eventName);\n\n // Set custom tags for properties\n if (properties) {\n Object.entries(properties).forEach(([key, value]) => {\n clarity('set', key, String(value));\n });\n }\n }\n } catch (error) {\n logger('error', 'Failed to track Clarity event', { eventName, error });\n }\n}\n\n/**\n * Builds a tracking event name from prefix, page and event segments.\n * The prefix is expected to already include a trailing separator (e.g. 'nuvempago_lending_').\n * Page is optional — when absent the segment is omitted from the name.\n *\n * @example\n * buildEventName('nuvempago_lending_', 'dashboard', 'charge', 'view')\n * // → 'nuvempago_lending_dashboard_charge_view'\n *\n * buildEventName('nuvempago_lending_', undefined, 'charge', 'view')\n * // → 'nuvempago_lending_charge_view'\n */\nexport function buildEventName(\n prefix: string,\n page: string | undefined,\n context: string,\n event: string,\n): string {\n // Prefix already contains its trailing separator — join only the remaining segments\n const segments = [page, context, event].filter(Boolean);\n return `${prefix}${segments.join('_')}`;\n}\n\n/**\n * Builds a TrackingProperties object from a loose record, dropping entries\n * whose value is undefined so callers don't need to guard optional fields.\n */\nexport function buildTrackingProperties(\n source: Record<string, TrackingValue | undefined>,\n): TrackingProperties {\n return Object.fromEntries(\n Object.entries(source).filter(\n (entry): entry is [string, TrackingValue] => entry[1] !== undefined,\n ),\n );\n}\n\n/**\n * Track event with both Amplitude and Clarity (fail silently)\n */\nexport function trackEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n trackAmplitudeEvent(eventName, properties, log);\n trackClarityEvent(eventName, properties, log);\n}\n\n/**\n * Clarity command API shape — kept module-local to avoid polluting the\n * consumer's global Window type with a conflicting declaration.\n * https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-api\n */\ntype ClarityCommand =\n | 'init'\n | 'event'\n | 'set'\n | 'identify'\n | 'consent'\n | 'upgrade';\n\ntype ClarityFn = {\n (command: ClarityCommand, ...args: string[]): void;\n q?: string[][];\n};\n\n/** Access window.clarity without declaring a global augmentation */\nfunction getClarity(): ClarityFn | undefined {\n return (window as unknown as Record<string, unknown>).clarity as\n | ClarityFn\n | undefined;\n}\n","import { createContext, useContext, useEffect, useMemo } from 'react';\nimport { SWRConfig } from 'swr';\nimport type {\n LiveStateFetcher,\n AnalyticsConfig,\n TrackingProperties,\n LiveStateResponse,\n CtaConfig,\n LiveStateProviderProps,\n} from '../types';\nimport { initializeAmplitude, initializeClarity } from '../utils/analytics';\nimport { createLogger, type LoggerFn } from '../utils/logger';\n\ninterface LiveStateContextValue {\n fetcher: LiveStateFetcher;\n analytics?: AnalyticsConfig;\n onEvent?: (eventName: string, properties?: TrackingProperties) => void;\n onNavigate?: (cta: CtaConfig) => void;\n mockData?: LiveStateResponse | null;\n disabled?: boolean;\n log: LoggerFn;\n}\n\nconst LiveStateContext = createContext<LiveStateContextValue | null>(null);\n\n/**\n * LiveStateProvider\n *\n * Root-level provider that configures fetcher function and analytics.\n * Initializes Amplitude and Clarity on mount.\n *\n * The optional `onEvent` callback is fired on every tracking event before\n * sending to Amplitude/Clarity — useful for simulators and debugging tools.\n *\n * The optional `onLog` callback receives all internal lib logs — route them\n * to your APM (Datadog, Sentry, etc.) to avoid relying on console.*.\n *\n * See examples/ directory for usage examples.\n */\nexport function LiveStateProvider({\n children,\n fetcher,\n analytics,\n onEvent,\n onLog,\n onNavigate,\n mockData,\n disabled = false,\n cacheProvider,\n}: LiveStateProviderProps) {\n const log = useMemo(() => createLogger(onLog), [onLog]);\n\n useEffect(() => {\n if (disabled) return;\n\n if (analytics?.amplitudeKey) {\n initializeAmplitude(analytics.amplitudeKey, log);\n }\n\n if (analytics?.clarityProjectId) {\n initializeClarity(analytics.clarityProjectId, log);\n }\n }, [analytics, disabled, log]);\n\n const contextValue = useMemo(\n () => ({ fetcher, analytics, onEvent, onNavigate, mockData, disabled, log }),\n [fetcher, analytics, onEvent, onNavigate, mockData, disabled, log],\n );\n\n return (\n <SWRConfig value={{ provider: cacheProvider ? () => cacheProvider : () => new Map() }}>\n <LiveStateContext.Provider value={contextValue}>\n {children}\n </LiveStateContext.Provider>\n </SWRConfig>\n );\n}\n\n/**\n * useLiveStateContext\n *\n * Internal hook to access LiveStateContext\n */\nexport function useLiveStateContext() {\n const context = useContext(LiveStateContext);\n\n if (!context) {\n throw new Error('useLiveState must be used within LiveStateProvider');\n }\n\n return context;\n}\n"],"mappings":";;;;;AAeA,IAAM,KAA2B,GAAO,GAAS,MAAY;CAC3D,IAAM,IAAS;AACf,CAAI,MAAU,UACZ,QAAQ,MAAM,GAAQ,GAAS,GAAI,IAAU,CAAC,EAAQ,GAAG,EAAE,CAAE,GAE7D,QAAQ,KAAK,GAAQ,GAAS,GAAI,IAAU,CAAC,EAAQ,GAAG,EAAE,CAAE;;AAchE,SAAgB,EAAa,GAA4B;AACvD,SAAQ,GAAO,GAAS,MAAY;AAClC,EAAI,IACF,EAAM,GAAO,GAAS,EAAQ,GAE9B,EAAc,GAAO,GAAS,EAAQ;;;;;AC/B5C,IAAM,IAAoB,EAAU,gBAAgB;AAKpD,SAAgB,EAAoB,GAAgB,GAAsB;CACxE,IAAM,IAAS,EAAa,EAAI;AAChC,KAAI;AACF,MAAI,CAAC,GAAQ;AACX,KAAO,QAAQ,iCAAiC;AAChD;;AAGF,IAAkB,KAAK,GAAQ,EAC7B,iBAAiB,IAClB,CAAC;UACK,GAAO;AACd,IAAO,SAAS,kCAAkC,EAAE,UAAO,CAAC;;;AAOhE,eAAsB,EACpB,GACA,GACe;CACf,IAAM,IAAS,EAAa,EAAI;AAChC,KAAI;AAEF,MAAI,GAAY,EAAE;AAChB,KAAO,QAAQ,wCAAwC;AACvD;;EAIF,IAAM,IAAiB,KAAa,GAA2B;AAE/D,MAAI,CAAC,GAAgB;AACnB,KAAO,QAAQ,kCAAkC;AACjD;;AAKF,GADiB,MAAM,OAAO,uBAAuB,QAC7C,KAAK,EAAe;UACrB,GAAO;AACd,IAAO,SAAS,gCAAgC,EAAE,UAAO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,IAAM,IAAM,QAAc,EAAa,EAAM,EAAE,CAAC,EAAM,CAAC;AAEvD,SAAgB;AACV,QAEA,GAAW,gBACb,EAAoB,EAAU,cAAc,EAAI,EAG9C,GAAW,oBACb,EAAkB,EAAU,kBAAkB,EAAI;IAEnD;EAAC;EAAW;EAAU;EAAI,CAAC;CAE9B,IAAM,IAAe,SACZ;EAAE;EAAS;EAAW;EAAS;EAAY;EAAU;EAAU;EAAK,GAC3E;EAAC;EAAS;EAAW;EAAS;EAAY;EAAU;EAAU;EAAI,CACnE;AAED,QACE,kBAAC,GAAD;EAAW,OAAO,EAAE,UAAU,UAAsB,0BAAsB,IAAI,KAAK,EAAE;YACnF,kBAAC,EAAiB,UAAlB;GAA2B,OAAO;GAC/B;GACyB,CAAA;EAClB,CAAA;;AAShB,SAAgB,IAAsB;CACpC,IAAM,IAAU,EAAW,EAAiB;AAE5C,KAAI,CAAC,EACH,OAAU,MAAM,qDAAqD;AAGvE,QAAO"}
@@ -1,2 +1,2 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`react`),l=require(`swr`),u=require(`@amplitude/analytics-browser`);u=s(u,1);let d=require(`react/jsx-runtime`);var f=(e,t,n)=>{let r=`[LiveState]`;e===`error`?console.error(r,t,...n?[n]:[]):console.warn(r,t,...n?[n]:[])};function p(e){return(t,n,r)=>{e?e(t,n,r):f(t,n,r)}}var m=u.createInstance();function h(e,t){let n=p(t);try{if(!e){n(`warn`,`Amplitude API key not provided`);return}m.init(e,{defaultTracking:!1})}catch(e){n(`error`,`Failed to initialize Amplitude`,{error:e})}}async function g(e,t){let n=p(t);try{if(C()){n(`info`,`Clarity already initialized by client`);return}let t=e||_();if(!t){n(`warn`,`Clarity project ID not provided`);return}(await import(`@microsoft/clarity`)).default.init(t)}catch(e){n(`error`,`Failed to initialize Clarity`,{error:e})}}function _(){try{let e=document.querySelector(`script[src*="clarity.ms"]`);if(e)return e.getAttribute(`src`)?.match(/\/([a-z0-9]+)$/)?.[1];let t=C()?.q?.[0]?.[1];if(typeof t==`string`)return t}catch{}}function v(e,t,n){let r=p(n);try{m.track(e,t)}catch(t){r(`error`,`Failed to track Amplitude event`,{eventName:e,error:t})}}function y(e,t,n){let r=p(n);try{let n=C();n&&(n(`event`,e),t&&Object.entries(t).forEach(([e,t])=>{n(`set`,e,String(t))}))}catch(t){r(`error`,`Failed to track Clarity event`,{eventName:e,error:t})}}function b(e,t,n,r){return`${e}${[t,n,r].filter(Boolean).join(`_`)}`}function x(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function S(e,t,n){v(e,t,n),y(e,t,n)}function C(){return window.clarity}var w=(0,c.createContext)(null);function T({children:e,fetcher:t,analytics:n,onEvent:r,onLog:i,onNavigate:a,mockData:o,disabled:s=!1}){let u=(0,c.useMemo)(()=>p(i),[i]);(0,c.useEffect)(()=>{s||(n?.amplitudeKey&&h(n.amplitudeKey,u),n?.clarityProjectId&&g(n.clarityProjectId,u))},[n,s,u]);let f=(0,c.useMemo)(()=>({fetcher:t,analytics:n,onEvent:r,onNavigate:a,mockData:o,disabled:s,log:u}),[t,n,r,a,o,s,u]);return(0,d.jsx)(l.SWRConfig,{value:{provider:()=>new Map},children:(0,d.jsx)(w.Provider,{value:f,children:e})})}function E(){let e=(0,c.useContext)(w);if(!e)throw Error(`useLiveState must be used within LiveStateProvider`);return e}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return T}});
2
- //# sourceMappingURL=LiveStateProvider-ByK7lK2v.cjs.map
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`react`),l=require(`swr`),u=require(`@amplitude/analytics-browser`);u=s(u,1);let d=require(`react/jsx-runtime`);var f=(e,t,n)=>{let r=`[LiveState]`;e===`error`?console.error(r,t,...n?[n]:[]):console.warn(r,t,...n?[n]:[])};function p(e){return(t,n,r)=>{e?e(t,n,r):f(t,n,r)}}var m=u.createInstance();function h(e,t){let n=p(t);try{if(!e){n(`warn`,`Amplitude API key not provided`);return}m.init(e,{defaultTracking:!1})}catch(e){n(`error`,`Failed to initialize Amplitude`,{error:e})}}async function g(e,t){let n=p(t);try{if(C()){n(`info`,`Clarity already initialized by client`);return}let t=e||_();if(!t){n(`warn`,`Clarity project ID not provided`);return}(await import(`@microsoft/clarity`)).default.init(t)}catch(e){n(`error`,`Failed to initialize Clarity`,{error:e})}}function _(){try{let e=document.querySelector(`script[src*="clarity.ms"]`);if(e)return e.getAttribute(`src`)?.match(/\/([a-z0-9]+)$/)?.[1];let t=C()?.q?.[0]?.[1];if(typeof t==`string`)return t}catch{}}function v(e,t,n){let r=p(n);try{m.track(e,t)}catch(t){r(`error`,`Failed to track Amplitude event`,{eventName:e,error:t})}}function y(e,t,n){let r=p(n);try{let n=C();n&&(n(`event`,e),t&&Object.entries(t).forEach(([e,t])=>{n(`set`,e,String(t))}))}catch(t){r(`error`,`Failed to track Clarity event`,{eventName:e,error:t})}}function b(e,t,n,r){return`${e}${[t,n,r].filter(Boolean).join(`_`)}`}function x(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function S(e,t,n){v(e,t,n),y(e,t,n)}function C(){return window.clarity}var w=(0,c.createContext)(null);function T({children:e,fetcher:t,analytics:n,onEvent:r,onLog:i,onNavigate:a,mockData:o,disabled:s=!1,cacheProvider:u}){let f=(0,c.useMemo)(()=>p(i),[i]);(0,c.useEffect)(()=>{s||(n?.amplitudeKey&&h(n.amplitudeKey,f),n?.clarityProjectId&&g(n.clarityProjectId,f))},[n,s,f]);let m=(0,c.useMemo)(()=>({fetcher:t,analytics:n,onEvent:r,onNavigate:a,mockData:o,disabled:s,log:f}),[t,n,r,a,o,s,f]);return(0,d.jsx)(l.SWRConfig,{value:{provider:u?()=>u:()=>new Map},children:(0,d.jsx)(w.Provider,{value:m,children:e})})}function E(){let e=(0,c.useContext)(w);if(!e)throw Error(`useLiveState must be used within LiveStateProvider`);return e}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return T}});
2
+ //# sourceMappingURL=LiveStateProvider-L2Oxk6mo.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"LiveStateProvider-ByK7lK2v.cjs","names":[],"sources":["../src/utils/logger.ts","../src/utils/analytics.ts","../src/providers/LiveStateProvider.tsx"],"sourcesContent":["import type { LogLevel } from '../types';\n\n/**\n * Logger function type — matches the signature of LiveStateProviderProps.onLog.\n */\nexport type LoggerFn = (\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n) => void;\n\n/**\n * Default logger — falls back to console.* when no onLog is provided.\n * Uses console.warn for 'info' and 'warn', console.error for 'error'.\n */\nconst defaultLogger: LoggerFn = (level, message, context) => {\n const prefix = '[LiveState]';\n if (level === 'error') {\n console.error(prefix, message, ...(context ? [context] : []));\n } else {\n console.warn(prefix, message, ...(context ? [context] : []));\n }\n};\n\n/**\n * Creates a logger bound to an optional consumer-provided onLog callback.\n * When onLog is provided it is called exclusively — the default console.*\n * fallback does NOT run, giving the consumer full control over output.\n *\n * @example\n * const log = createLogger(onLog);\n * log('warn', 'Amplitude API key not provided');\n * log('error', 'Failed to fetch', { url: '/v1/live-state', status: 500 });\n */\nexport function createLogger(onLog?: LoggerFn): LoggerFn {\n return (level, message, context) => {\n if (onLog) {\n onLog(level, message, context);\n } else {\n defaultLogger(level, message, context);\n }\n };\n}\n","import * as amplitude from '@amplitude/analytics-browser';\nimport type { TrackingProperties, TrackingValue } from '../types';\nimport { createLogger, type LoggerFn } from './logger';\n\n/**\n * Isolated Amplitude instance for the lib — avoids conflicts with the\n * consumer app's own Amplitude instance when both coexist on the same page.\n */\nconst amplitudeInstance = amplitude.createInstance();\n\n/**\n * Initialize Amplitude (fail silently)\n */\nexport function initializeAmplitude(apiKey: string, log?: LoggerFn): void {\n const logger = createLogger(log);\n try {\n if (!apiKey) {\n logger('warn', 'Amplitude API key not provided');\n return;\n }\n\n amplitudeInstance.init(apiKey, {\n defaultTracking: false,\n });\n } catch (error) {\n logger('error', 'Failed to initialize Amplitude', { error });\n }\n}\n\n/**\n * Initialize Clarity (fail silently)\n */\nexport async function initializeClarity(\n projectId?: string,\n log?: LoggerFn,\n): Promise<void> {\n const logger = createLogger(log);\n try {\n // Check if Clarity is already loaded by the client\n if (getClarity()) {\n logger('info', 'Clarity already initialized by client');\n return;\n }\n\n // If client provided project ID, use it\n const finalProjectId = projectId || getClientClarityProjectId();\n\n if (!finalProjectId) {\n logger('warn', 'Clarity project ID not provided');\n return;\n }\n\n // Initialize Clarity with project ID\n const Clarity = (await import('@microsoft/clarity')).default;\n Clarity.init(finalProjectId);\n } catch (error) {\n logger('error', 'Failed to initialize Clarity', { error });\n }\n}\n\n/**\n * Try to extract Clarity project ID from client's installation\n */\nfunction getClientClarityProjectId(): string | undefined {\n try {\n // Check if Clarity script tag exists\n const clarityScript = document.querySelector('script[src*=\"clarity.ms\"]');\n if (clarityScript) {\n const src = clarityScript.getAttribute('src');\n const match = src?.match(/\\/([a-z0-9]+)$/);\n return match?.[1];\n }\n\n // Check global clarity config: shape is clarity.q = [['init', projectId, ...]]\n const projectId = getClarity()?.q?.[0]?.[1];\n if (typeof projectId === 'string') {\n return projectId;\n }\n } catch {\n // Fail silently\n }\n\n return undefined;\n}\n\n/**\n * Track event with Amplitude (fail silently)\n */\nexport function trackAmplitudeEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n amplitudeInstance.track(eventName, properties);\n } catch (error) {\n logger('error', 'Failed to track Amplitude event', { eventName, error });\n }\n}\n\n/**\n * Track event with Clarity (fail silently)\n */\nexport function trackClarityEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n const clarity = getClarity();\n if (clarity) {\n clarity('event', eventName);\n\n // Set custom tags for properties\n if (properties) {\n Object.entries(properties).forEach(([key, value]) => {\n clarity('set', key, String(value));\n });\n }\n }\n } catch (error) {\n logger('error', 'Failed to track Clarity event', { eventName, error });\n }\n}\n\n/**\n * Builds a tracking event name from prefix, page and event segments.\n * The prefix is expected to already include a trailing separator (e.g. 'nuvempago_lending_').\n * Page is optional — when absent the segment is omitted from the name.\n *\n * @example\n * buildEventName('nuvempago_lending_', 'dashboard', 'charge', 'view')\n * // → 'nuvempago_lending_dashboard_charge_view'\n *\n * buildEventName('nuvempago_lending_', undefined, 'charge', 'view')\n * // → 'nuvempago_lending_charge_view'\n */\nexport function buildEventName(\n prefix: string,\n page: string | undefined,\n context: string,\n event: string,\n): string {\n // Prefix already contains its trailing separator — join only the remaining segments\n const segments = [page, context, event].filter(Boolean);\n return `${prefix}${segments.join('_')}`;\n}\n\n/**\n * Builds a TrackingProperties object from a loose record, dropping entries\n * whose value is undefined so callers don't need to guard optional fields.\n */\nexport function buildTrackingProperties(\n source: Record<string, TrackingValue | undefined>,\n): TrackingProperties {\n return Object.fromEntries(\n Object.entries(source).filter(\n (entry): entry is [string, TrackingValue] => entry[1] !== undefined,\n ),\n );\n}\n\n/**\n * Track event with both Amplitude and Clarity (fail silently)\n */\nexport function trackEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n trackAmplitudeEvent(eventName, properties, log);\n trackClarityEvent(eventName, properties, log);\n}\n\n/**\n * Clarity command API shape — kept module-local to avoid polluting the\n * consumer's global Window type with a conflicting declaration.\n * https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-api\n */\ntype ClarityCommand =\n | 'init'\n | 'event'\n | 'set'\n | 'identify'\n | 'consent'\n | 'upgrade';\n\ntype ClarityFn = {\n (command: ClarityCommand, ...args: string[]): void;\n q?: string[][];\n};\n\n/** Access window.clarity without declaring a global augmentation */\nfunction getClarity(): ClarityFn | undefined {\n return (window as unknown as Record<string, unknown>).clarity as\n | ClarityFn\n | undefined;\n}\n","import { createContext, useContext, useEffect, useMemo } from 'react';\nimport { SWRConfig } from 'swr';\nimport type {\n LiveStateFetcher,\n AnalyticsConfig,\n TrackingProperties,\n LiveStateResponse,\n CtaConfig,\n LiveStateProviderProps,\n} from '../types';\nimport { initializeAmplitude, initializeClarity } from '../utils/analytics';\nimport { createLogger, type LoggerFn } from '../utils/logger';\n\ninterface LiveStateContextValue {\n fetcher: LiveStateFetcher;\n analytics?: AnalyticsConfig;\n onEvent?: (eventName: string, properties?: TrackingProperties) => void;\n onNavigate?: (cta: CtaConfig) => void;\n mockData?: LiveStateResponse | null;\n disabled?: boolean;\n log: LoggerFn;\n}\n\nconst LiveStateContext = createContext<LiveStateContextValue | null>(null);\n\n/**\n * LiveStateProvider\n *\n * Root-level provider that configures fetcher function and analytics.\n * Initializes Amplitude and Clarity on mount.\n *\n * The optional `onEvent` callback is fired on every tracking event before\n * sending to Amplitude/Clarity — useful for simulators and debugging tools.\n *\n * The optional `onLog` callback receives all internal lib logs — route them\n * to your APM (Datadog, Sentry, etc.) to avoid relying on console.*.\n *\n * See examples/ directory for usage examples.\n */\nexport function LiveStateProvider({\n children,\n fetcher,\n analytics,\n onEvent,\n onLog,\n onNavigate,\n mockData,\n disabled = false,\n}: LiveStateProviderProps) {\n const log = useMemo(() => createLogger(onLog), [onLog]);\n\n useEffect(() => {\n if (disabled) return;\n\n if (analytics?.amplitudeKey) {\n initializeAmplitude(analytics.amplitudeKey, log);\n }\n\n if (analytics?.clarityProjectId) {\n initializeClarity(analytics.clarityProjectId, log);\n }\n }, [analytics, disabled, log]);\n\n const contextValue = useMemo(\n () => ({ fetcher, analytics, onEvent, onNavigate, mockData, disabled, log }),\n [fetcher, analytics, onEvent, onNavigate, mockData, disabled, log],\n );\n\n return (\n <SWRConfig value={{ provider: () => new Map() }}>\n <LiveStateContext.Provider value={contextValue}>\n {children}\n </LiveStateContext.Provider>\n </SWRConfig>\n );\n}\n\n/**\n * useLiveStateContext\n *\n * Internal hook to access LiveStateContext\n */\nexport function useLiveStateContext() {\n const context = useContext(LiveStateContext);\n\n if (!context) {\n throw new Error('useLiveState must be used within LiveStateProvider');\n }\n\n return context;\n}\n"],"mappings":"4lBAeA,IAAM,GAA2B,EAAO,EAAS,IAAY,CAC3D,IAAM,EAAS,cACX,IAAU,QACZ,QAAQ,MAAM,EAAQ,EAAS,GAAI,EAAU,CAAC,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gB,IAAI,IAAO,WAC7C,EAAA,EAAA,KAAC,EAAiB,SAAlB,CAA2B,MAAO,EAC/B,WACyB,CAAA,CAClB,CAAA,CAShB,SAAgB,GAAsB,CACpC,IAAM,GAAA,EAAA,EAAA,YAAqB,EAAiB,CAE5C,GAAI,CAAC,EACH,MAAU,MAAM,qDAAqD,CAGvE,OAAO"}
1
+ {"version":3,"file":"LiveStateProvider-L2Oxk6mo.cjs","names":[],"sources":["../src/utils/logger.ts","../src/utils/analytics.ts","../src/providers/LiveStateProvider.tsx"],"sourcesContent":["import type { LogLevel } from '../types';\n\n/**\n * Logger function type — matches the signature of LiveStateProviderProps.onLog.\n */\nexport type LoggerFn = (\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n) => void;\n\n/**\n * Default logger — falls back to console.* when no onLog is provided.\n * Uses console.warn for 'info' and 'warn', console.error for 'error'.\n */\nconst defaultLogger: LoggerFn = (level, message, context) => {\n const prefix = '[LiveState]';\n if (level === 'error') {\n console.error(prefix, message, ...(context ? [context] : []));\n } else {\n console.warn(prefix, message, ...(context ? [context] : []));\n }\n};\n\n/**\n * Creates a logger bound to an optional consumer-provided onLog callback.\n * When onLog is provided it is called exclusively — the default console.*\n * fallback does NOT run, giving the consumer full control over output.\n *\n * @example\n * const log = createLogger(onLog);\n * log('warn', 'Amplitude API key not provided');\n * log('error', 'Failed to fetch', { url: '/v1/live-state', status: 500 });\n */\nexport function createLogger(onLog?: LoggerFn): LoggerFn {\n return (level, message, context) => {\n if (onLog) {\n onLog(level, message, context);\n } else {\n defaultLogger(level, message, context);\n }\n };\n}\n","import * as amplitude from '@amplitude/analytics-browser';\nimport type { TrackingProperties, TrackingValue } from '../types';\nimport { createLogger, type LoggerFn } from './logger';\n\n/**\n * Isolated Amplitude instance for the lib — avoids conflicts with the\n * consumer app's own Amplitude instance when both coexist on the same page.\n */\nconst amplitudeInstance = amplitude.createInstance();\n\n/**\n * Initialize Amplitude (fail silently)\n */\nexport function initializeAmplitude(apiKey: string, log?: LoggerFn): void {\n const logger = createLogger(log);\n try {\n if (!apiKey) {\n logger('warn', 'Amplitude API key not provided');\n return;\n }\n\n amplitudeInstance.init(apiKey, {\n defaultTracking: false,\n });\n } catch (error) {\n logger('error', 'Failed to initialize Amplitude', { error });\n }\n}\n\n/**\n * Initialize Clarity (fail silently)\n */\nexport async function initializeClarity(\n projectId?: string,\n log?: LoggerFn,\n): Promise<void> {\n const logger = createLogger(log);\n try {\n // Check if Clarity is already loaded by the client\n if (getClarity()) {\n logger('info', 'Clarity already initialized by client');\n return;\n }\n\n // If client provided project ID, use it\n const finalProjectId = projectId || getClientClarityProjectId();\n\n if (!finalProjectId) {\n logger('warn', 'Clarity project ID not provided');\n return;\n }\n\n // Initialize Clarity with project ID\n const Clarity = (await import('@microsoft/clarity')).default;\n Clarity.init(finalProjectId);\n } catch (error) {\n logger('error', 'Failed to initialize Clarity', { error });\n }\n}\n\n/**\n * Try to extract Clarity project ID from client's installation\n */\nfunction getClientClarityProjectId(): string | undefined {\n try {\n // Check if Clarity script tag exists\n const clarityScript = document.querySelector('script[src*=\"clarity.ms\"]');\n if (clarityScript) {\n const src = clarityScript.getAttribute('src');\n const match = src?.match(/\\/([a-z0-9]+)$/);\n return match?.[1];\n }\n\n // Check global clarity config: shape is clarity.q = [['init', projectId, ...]]\n const projectId = getClarity()?.q?.[0]?.[1];\n if (typeof projectId === 'string') {\n return projectId;\n }\n } catch {\n // Fail silently\n }\n\n return undefined;\n}\n\n/**\n * Track event with Amplitude (fail silently)\n */\nexport function trackAmplitudeEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n amplitudeInstance.track(eventName, properties);\n } catch (error) {\n logger('error', 'Failed to track Amplitude event', { eventName, error });\n }\n}\n\n/**\n * Track event with Clarity (fail silently)\n */\nexport function trackClarityEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n const logger = createLogger(log);\n try {\n const clarity = getClarity();\n if (clarity) {\n clarity('event', eventName);\n\n // Set custom tags for properties\n if (properties) {\n Object.entries(properties).forEach(([key, value]) => {\n clarity('set', key, String(value));\n });\n }\n }\n } catch (error) {\n logger('error', 'Failed to track Clarity event', { eventName, error });\n }\n}\n\n/**\n * Builds a tracking event name from prefix, page and event segments.\n * The prefix is expected to already include a trailing separator (e.g. 'nuvempago_lending_').\n * Page is optional — when absent the segment is omitted from the name.\n *\n * @example\n * buildEventName('nuvempago_lending_', 'dashboard', 'charge', 'view')\n * // → 'nuvempago_lending_dashboard_charge_view'\n *\n * buildEventName('nuvempago_lending_', undefined, 'charge', 'view')\n * // → 'nuvempago_lending_charge_view'\n */\nexport function buildEventName(\n prefix: string,\n page: string | undefined,\n context: string,\n event: string,\n): string {\n // Prefix already contains its trailing separator — join only the remaining segments\n const segments = [page, context, event].filter(Boolean);\n return `${prefix}${segments.join('_')}`;\n}\n\n/**\n * Builds a TrackingProperties object from a loose record, dropping entries\n * whose value is undefined so callers don't need to guard optional fields.\n */\nexport function buildTrackingProperties(\n source: Record<string, TrackingValue | undefined>,\n): TrackingProperties {\n return Object.fromEntries(\n Object.entries(source).filter(\n (entry): entry is [string, TrackingValue] => entry[1] !== undefined,\n ),\n );\n}\n\n/**\n * Track event with both Amplitude and Clarity (fail silently)\n */\nexport function trackEvent(\n eventName: string,\n properties?: TrackingProperties,\n log?: LoggerFn,\n): void {\n trackAmplitudeEvent(eventName, properties, log);\n trackClarityEvent(eventName, properties, log);\n}\n\n/**\n * Clarity command API shape — kept module-local to avoid polluting the\n * consumer's global Window type with a conflicting declaration.\n * https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-api\n */\ntype ClarityCommand =\n | 'init'\n | 'event'\n | 'set'\n | 'identify'\n | 'consent'\n | 'upgrade';\n\ntype ClarityFn = {\n (command: ClarityCommand, ...args: string[]): void;\n q?: string[][];\n};\n\n/** Access window.clarity without declaring a global augmentation */\nfunction getClarity(): ClarityFn | undefined {\n return (window as unknown as Record<string, unknown>).clarity as\n | ClarityFn\n | undefined;\n}\n","import { createContext, useContext, useEffect, useMemo } from 'react';\nimport { SWRConfig } from 'swr';\nimport type {\n LiveStateFetcher,\n AnalyticsConfig,\n TrackingProperties,\n LiveStateResponse,\n CtaConfig,\n LiveStateProviderProps,\n} from '../types';\nimport { initializeAmplitude, initializeClarity } from '../utils/analytics';\nimport { createLogger, type LoggerFn } from '../utils/logger';\n\ninterface LiveStateContextValue {\n fetcher: LiveStateFetcher;\n analytics?: AnalyticsConfig;\n onEvent?: (eventName: string, properties?: TrackingProperties) => void;\n onNavigate?: (cta: CtaConfig) => void;\n mockData?: LiveStateResponse | null;\n disabled?: boolean;\n log: LoggerFn;\n}\n\nconst LiveStateContext = createContext<LiveStateContextValue | null>(null);\n\n/**\n * LiveStateProvider\n *\n * Root-level provider that configures fetcher function and analytics.\n * Initializes Amplitude and Clarity on mount.\n *\n * The optional `onEvent` callback is fired on every tracking event before\n * sending to Amplitude/Clarity — useful for simulators and debugging tools.\n *\n * The optional `onLog` callback receives all internal lib logs — route them\n * to your APM (Datadog, Sentry, etc.) to avoid relying on console.*.\n *\n * See examples/ directory for usage examples.\n */\nexport function LiveStateProvider({\n children,\n fetcher,\n analytics,\n onEvent,\n onLog,\n onNavigate,\n mockData,\n disabled = false,\n cacheProvider,\n}: LiveStateProviderProps) {\n const log = useMemo(() => createLogger(onLog), [onLog]);\n\n useEffect(() => {\n if (disabled) return;\n\n if (analytics?.amplitudeKey) {\n initializeAmplitude(analytics.amplitudeKey, log);\n }\n\n if (analytics?.clarityProjectId) {\n initializeClarity(analytics.clarityProjectId, log);\n }\n }, [analytics, disabled, log]);\n\n const contextValue = useMemo(\n () => ({ fetcher, analytics, onEvent, onNavigate, mockData, disabled, log }),\n [fetcher, analytics, onEvent, onNavigate, mockData, disabled, log],\n );\n\n return (\n <SWRConfig value={{ provider: cacheProvider ? () => cacheProvider : () => new Map() }}>\n <LiveStateContext.Provider value={contextValue}>\n {children}\n </LiveStateContext.Provider>\n </SWRConfig>\n );\n}\n\n/**\n * useLiveStateContext\n *\n * Internal hook to access LiveStateContext\n */\nexport function useLiveStateContext() {\n const context = useContext(LiveStateContext);\n\n if (!context) {\n throw new Error('useLiveState must be used within LiveStateProvider');\n }\n\n return context;\n}\n"],"mappings":"4lBAeA,IAAM,GAA2B,EAAO,EAAS,IAAY,CAC3D,IAAM,EAAS,cACX,IAAU,QACZ,QAAQ,MAAM,EAAQ,EAAS,GAAI,EAAU,CAAC,EAAQ,CAAG,EAAE,CAAE,CAE7D,QAAQ,KAAK,EAAQ,EAAS,GAAI,EAAU,CAAC,EAAQ,CAAG,EAAE,CAAE,EAchE,SAAgB,EAAa,EAA4B,CACvD,OAAQ,EAAO,EAAS,IAAY,CAC9B,EACF,EAAM,EAAO,EAAS,EAAQ,CAE9B,EAAc,EAAO,EAAS,EAAQ,EC/B5C,IAAM,EAAoB,EAAU,gBAAgB,CAKpD,SAAgB,EAAoB,EAAgB,EAAsB,CACxE,IAAM,EAAS,EAAa,EAAI,CAChC,GAAI,CACF,GAAI,CAAC,EAAQ,CACX,EAAO,OAAQ,iCAAiC,CAChD,OAGF,EAAkB,KAAK,EAAQ,CAC7B,gBAAiB,GAClB,CAAC,OACK,EAAO,CACd,EAAO,QAAS,iCAAkC,CAAE,QAAO,CAAC,EAOhE,eAAsB,EACpB,EACA,EACe,CACf,IAAM,EAAS,EAAa,EAAI,CAChC,GAAI,CAEF,GAAI,GAAY,CAAE,CAChB,EAAO,OAAQ,wCAAwC,CACvD,OAIF,IAAM,EAAiB,GAAa,GAA2B,CAE/D,GAAI,CAAC,EAAgB,CACnB,EAAO,OAAQ,kCAAkC,CACjD,QAIe,MAAM,OAAO,uBAAuB,QAC7C,KAAK,EAAe,OACrB,EAAO,CACd,EAAO,QAAS,+BAAgC,CAAE,QAAO,CAAC,EAO9D,SAAS,GAAgD,CACvD,GAAI,CAEF,IAAM,EAAgB,SAAS,cAAc,4BAA4B,CACzE,GAAI,EAGF,OAFY,EAAc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AU,aAAc,EAAI,CAG9C,GAAW,kBACb,EAAkB,EAAU,iBAAkB,EAAI,GAEnD,CAAC,EAAW,EAAU,EAAI,CAAC,CAE9B,IAAM,GAAA,EAAA,EAAA,cACG,CAAE,UAAS,YAAW,UAAS,aAAY,WAAU,WAAU,MAAK,EAC3E,CAAC,EAAS,EAAW,EAAS,EAAY,EAAU,EAAU,EAAI,CACnE,CAED,OACE,EAAA,EAAA,KAAC,EAAA,UAAD,CAAW,MAAO,CAAE,SAAU,MAAsB,MAAsB,IAAI,IAAO,WACnF,EAAA,EAAA,KAAC,EAAiB,SAAlB,CAA2B,MAAO,EAC/B,WACyB,CAAA,CAClB,CAAA,CAShB,SAAgB,GAAsB,CACpC,IAAM,GAAA,EAAA,EAAA,YAAqB,EAAiB,CAE5C,GAAI,CAAC,EACH,MAAU,MAAM,qDAAqD,CAGvE,OAAO"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./LiveStateProvider-ByK7lK2v.cjs`);let t=require(`react`),n=require(`swr`);n=e.s(n,1);let r=require(`react/jsx-runtime`),i=require(`@nimbus-ds/components`),a=require(`@nimbus-ds/icons`);function o(){let{fetcher:t,mockData:r,log:i}=e.n(),a=r!==void 0,{data:o,error:s,isLoading:c,mutate:l}=(0,n.default)(a?null:`live-state`,t,{revalidateOnFocus:!1,revalidateOnReconnect:!0,dedupingInterval:6e4,shouldRetryOnError:!1,onError:e=>{i(`error`,`Failed to fetch live state`,{error:e})}}),u=async()=>{if(!a)try{await l()}catch(e){i(`error`,`Failed to refresh live state`,{error:e})}};return a?{liveState:r,isLoading:!1,isError:!1,error:null,refresh:u}:{liveState:o??null,isLoading:c,isError:s!=null,error:s??null,refresh:u}}function s(){let{onEvent:n,disabled:r,log:i}=e.n();return(0,t.useCallback)((t,a)=>{n?.(t,a),r||e.a(t,a,i)},[n,r,i])}var c=`@tiendanube/live-state:closable`,l=c;function u(){try{let e=localStorage.getItem(l);if(!e)return{};let t=JSON.parse(e);if(typeof t!=`object`||!t)return{};let n={};for(let[e,r]of Object.entries(t))if(!(typeof r!=`object`||!r)){n[e]={};for(let[t,i]of Object.entries(r))if(typeof i==`number`)n[e][t]={count:i,closedAt:0};else if(typeof i==`object`&&i){let r=i;n[e][t]={count:typeof r.count==`number`?r.count:0,closedAt:typeof r.closedAt==`number`?r.closedAt:0}}}return n}catch{return{}}}function d(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function f({context:e,id:n,maxCloseTimes:r=3,expiresIn:i}){let[a,o]=(0,t.useState)(null);return(0,t.useEffect)(()=>{if(!n){o(!0);return}let t=u(),a=t[e]?.[n];if(!a){o(!0);return}let{count:s,closedAt:c}=a;if(i!=null&&c>0&&Date.now()-c>i){let r={...t};r[e]&&(delete r[e][n],d(r)),o(!0);return}o(s<r)},[e,n,r,i]),{isVisible:a,close:(0,t.useCallback)(()=>{if(o(!1),!n)return;let t=u(),r=t[e]?.[n]?.count??0;d({...t,[e]:{...t[e]??{},[n]:{count:r+1,closedAt:Date.now()}}})},[e,n])}}function p(t,n){let r=e.o(n);try{switch(t.type){case`internal`:window.location.href=t.url;break;case`whatsapp`:{let e=t.whatsappMessage?`${t.url}?text=${encodeURIComponent(t.whatsappMessage)}`:t.url;window.open(e,`_blank`);break}case`external`:window.open(t.url,`_blank`);break;default:r(`warn`,`Unknown CTA type: ${t.type}`,{cta:t})}}catch(e){r(`error`,`Failed to handle CTA click`,{cta:t,error:e})}}var m=new Set([`strong`,`em`,`b`,`i`,`br`,`span`]),h=/<(script|style|iframe|object|embed|form|input|button|textarea|select|link|meta|head|body|html|svg|math)[\s\S]*?<\/\1\s*>|<(script|style|iframe|object|embed|form|input|button|textarea|select|link|meta|head|body|html|svg|math)[^>]*\/?>/gi;function g(e){return e.replace(h,``).replace(/<([a-zA-Z][a-zA-Z0-9]*)\s[^>]*>/g,`<$1>`).replace(/<\/?([a-zA-Z][a-zA-Z0-9]*)[^>]*>/g,(e,t)=>m.has(t.toLowerCase())?e:``)}function _(e){return/<[a-zA-Z][^>]*>/.test(e)}function v({content:e,...t}){if(_(e)){let n=g(e);return(0,r.jsx)(i.Text,{...t,children:(0,r.jsx)(`span`,{dangerouslySetInnerHTML:{__html:n}})})}return(0,r.jsx)(i.Text,{...t,children:e})}function y({data:n,trackingConfig:a,onClose:o,onCtaClick:c}){let l=s(),{log:u}=e.n(),d=n.type===`alert`?`danger`:`warning`,f=(0,t.useCallback)(()=>e.i({context:n.context,campaignId:n.campaignId,group:n.group,...n.metadata,...a.properties}),[n,a.properties]),m=(0,t.useCallback)(()=>{l(e.r(a.prefix,a.page,n.context,`click`),f()),c?c(n.cta):p(n.cta,u)},[n,a,f,l,c,u]),h=(0,t.useCallback)(()=>{l(e.r(a.prefix,a.page,n.context,`close`),f()),o?.()},[o,n,a,f,l]);return(0,t.useEffect)(()=>{l(e.r(a.prefix,a.page,n.context,`view`),f())},[]),(0,r.jsx)(i.Alert,{appearance:d,title:n.title,onRemove:o?h:void 0,children:(0,r.jsxs)(i.Box,{display:`flex`,alignItems:`flex-start`,gap:`3`,flexWrap:`wrap`,flexDirection:`column`,children:[(0,r.jsx)(i.Box,{flex:`1 1 auto`,minWidth:`220px`,children:(0,r.jsx)(v,{content:n.message})}),(0,r.jsx)(i.Box,{display:`flex`,justifyContent:`flex-end`,marginTop:`2`,children:(0,r.jsx)(i.Button,{appearance:`primary`,onClick:m,children:n.cta.label})})]})})}var b={blue:{background:`#0050C3`,icon:`#FFFFFF`},white:{background:`#FFFFFF`,icon:`#0059D5`}};function x({data:n,trackingConfig:o,defaultVariant:c=`blue`,onClose:l,isMobile:u,onCtaClick:d}){let f=s(),{log:m}=e.n(),h=n.variant||c,g=b[h],[_,y]=(0,t.useState)(()=>window.innerWidth<750);(0,t.useEffect)(()=>{let e=()=>y(window.innerWidth<750);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let x=u??_,S=(0,t.useCallback)(()=>e.i({context:n.context,campaignId:n.campaignId,group:n.group,...n.metadata,...o.properties}),[n,o.properties]),C=(0,t.useCallback)(()=>{f(e.r(o.prefix,o.page,n.context,`click`),S()),d?d(n.cta):p(n.cta,m)},[n,o,S,f,d,m]),w=(0,t.useCallback)(()=>{f(e.r(o.prefix,o.page,n.context,`close`),S()),l?.()},[l,n,o,S,f]);(0,t.useEffect)(()=>{f(e.r(o.prefix,o.page,n.context,`view`),S())},[]);let T=(0,r.jsx)(i.Link,{as:`a`,textDecoration:`none`,onClick:C,"data-testid":`live-state-cta-link`,children:(0,r.jsx)(i.Text,{color:`primary-interactive`,fontSize:`base`,children:n.cta.label})});return(0,r.jsx)(i.Card,{children:(0,r.jsxs)(i.Box,{display:`flex`,flexDirection:`row`,justifyContent:`space-between`,children:[(0,r.jsxs)(i.Box,{display:`flex`,gap:`4`,alignItems:x?`flex-start`:`center`,paddingRight:`1-5`,children:[(0,r.jsx)(i.Box,{minWidth:`32px`,children:(0,r.jsx)(`div`,{style:{width:32,height:32,borderRadius:`35%`,borderColor:h===`white`?`#E7E7E7`:`transparent`,borderWidth:1,borderStyle:`solid`,background:g.background,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,r.jsx)(a.MoneyIcon,{style:{color:g.icon}})})}),(0,r.jsxs)(i.Box,{display:`grid`,gap:`2`,children:[(0,r.jsxs)(i.Box,{children:[(0,r.jsx)(v,{content:n.title,fontSize:`base`,color:`neutral-textHigh`}),(0,r.jsx)(v,{content:n.message,fontSize:`base`,color:`neutral-textLow`})]}),x&&T]})]}),(!x||l)&&(0,r.jsxs)(i.Box,{display:`flex`,flexDirection:x?`column`:`row`,alignItems:x?`flex-end`:`center`,gap:`2`,children:[!x&&T,l&&(0,r.jsx)(`button`,{type:`button`,"data-testid":`live-state-close-button`,"aria-label":`Fechar notificação`,onClick:w,style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,r.jsx)(i.Icon,{source:(0,r.jsx)(a.CloseIcon,{width:`18px`,height:`18px`}),color:`neutral-interactive`})})]})]})})}function S({data:t,loading:n,trackingConfig:i,allowedContexts:a,defaultVariant:o,isMobile:s,onCtaClick:c}){let{log:l,onNavigate:u}=e.n(),d=c??u,{isVisible:p,close:m}=f({context:t?.context??``,id:t?.campaignId,maxCloseTimes:t?.metadata?.maxCloseTimes,expiresIn:t?.metadata?.expiresIn});if(n||!t)return null;if(!t.context||!t.type||!t.title||!t.message||!t.cta?.label||!t.cta?.url||!t.cta?.type)return l(`warn`,`Invalid payload, missing required fields`,{data:t}),null;if(a&&!a.includes(t.context)||p===null||!p)return null;let h=t.closable?m:void 0;return t.type===`alert`||t.type===`warning`?(0,r.jsx)(y,{data:t,onClose:h,trackingConfig:i,onCtaClick:d}):t.type===`info`?(0,r.jsx)(x,{data:t,onClose:h,trackingConfig:i,defaultVariant:o,isMobile:s,onCtaClick:d}):(l(`warn`,`Unknown type: ${t.type}`,{data:t}),null)}exports.LIVE_STATE_STORAGE_KEY=c,exports.LiveStateAlert=y,exports.LiveStateInfo=x,exports.LiveStateProvider=e.t,exports.LiveStateRenderer=S,exports.handleCtaClick=p,exports.trackEvent=e.a,exports.useLiveState=o,exports.useTrackEvent=s;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./LiveStateProvider-L2Oxk6mo.cjs`);let t=require(`react`),n=require(`swr`);n=e.s(n,1);let r=require(`react/jsx-runtime`),i=require(`@nimbus-ds/components`),a=require(`@nimbus-ds/icons`);function o(){let{fetcher:t,mockData:r,log:i}=e.n(),a=r!==void 0,{data:o,error:s,isLoading:c,mutate:l}=(0,n.default)(a?null:`live-state`,t,{revalidateOnFocus:!1,revalidateOnReconnect:!0,dedupingInterval:6e4,shouldRetryOnError:!1,onError:e=>{i(`error`,`Failed to fetch live state`,{error:e})}}),u=async()=>{if(!a)try{await l()}catch(e){i(`error`,`Failed to refresh live state`,{error:e})}};return a?{liveState:r,isLoading:!1,isError:!1,error:null,refresh:u}:{liveState:o??null,isLoading:c,isError:s!=null,error:s??null,refresh:u}}function s(){let{onEvent:n,disabled:r,log:i}=e.n();return(0,t.useCallback)((t,a)=>{n?.(t,a),r||e.a(t,a,i)},[n,r,i])}var c=`@tiendanube/live-state:closable`,l=c;function u(){try{let e=localStorage.getItem(l);if(!e)return{};let t=JSON.parse(e);if(typeof t!=`object`||!t)return{};let n={};for(let[e,r]of Object.entries(t))if(!(typeof r!=`object`||!r)){n[e]={};for(let[t,i]of Object.entries(r))if(typeof i==`number`)n[e][t]={count:i,closedAt:0};else if(typeof i==`object`&&i){let r=i;n[e][t]={count:typeof r.count==`number`?r.count:0,closedAt:typeof r.closedAt==`number`?r.closedAt:0}}}return n}catch{return{}}}function d(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function f({context:e,id:n,maxCloseTimes:r=3,expiresIn:i}){let[a,o]=(0,t.useState)(null);return(0,t.useEffect)(()=>{if(!n){o(!0);return}let t=u(),a=t[e]?.[n];if(!a){o(!0);return}let{count:s,closedAt:c}=a;if(i!=null&&c>0&&Date.now()-c>i){let r={...t};r[e]&&(delete r[e][n],d(r)),o(!0);return}o(s<r)},[e,n,r,i]),{isVisible:a,close:(0,t.useCallback)(()=>{if(o(!1),!n)return;let t=u(),r=t[e]?.[n]?.count??0;d({...t,[e]:{...t[e]??{},[n]:{count:r+1,closedAt:Date.now()}}})},[e,n])}}function p(t,n){let r=e.o(n);try{switch(t.type){case`internal`:window.location.href=t.url;break;case`whatsapp`:{let e=t.whatsappMessage?`${t.url}?text=${encodeURIComponent(t.whatsappMessage)}`:t.url;window.open(e,`_blank`);break}case`external`:window.open(t.url,`_blank`);break;default:r(`warn`,`Unknown CTA type: ${t.type}`,{cta:t})}}catch(e){r(`error`,`Failed to handle CTA click`,{cta:t,error:e})}}var m=new Set([`strong`,`em`,`b`,`i`,`br`,`span`]),h=/<(script|style|iframe|object|embed|form|input|button|textarea|select|link|meta|head|body|html|svg|math)[\s\S]*?<\/\1\s*>|<(script|style|iframe|object|embed|form|input|button|textarea|select|link|meta|head|body|html|svg|math)[^>]*\/?>/gi;function g(e){return e.replace(h,``).replace(/<([a-zA-Z][a-zA-Z0-9]*)\s[^>]*>/g,`<$1>`).replace(/<\/?([a-zA-Z][a-zA-Z0-9]*)[^>]*>/g,(e,t)=>m.has(t.toLowerCase())?e:``)}function _(e){return/<[a-zA-Z][^>]*>/.test(e)}function v({content:e,...t}){if(_(e)){let n=g(e);return(0,r.jsx)(i.Text,{...t,children:(0,r.jsx)(`span`,{dangerouslySetInnerHTML:{__html:n}})})}return(0,r.jsx)(i.Text,{...t,children:e})}function y({data:n,trackingConfig:a,onClose:o,onCtaClick:c}){let l=s(),{log:u}=e.n(),d=n.type===`alert`?`danger`:`warning`,f=(0,t.useCallback)(()=>e.i({context:n.context,campaignId:n.campaignId,group:n.group,...n.metadata,...a.properties}),[n,a.properties]),m=(0,t.useCallback)(()=>{l(e.r(a.prefix,a.page,n.context,`click`),f()),c?c(n.cta):p(n.cta,u)},[n,a,f,l,c,u]),h=(0,t.useCallback)(()=>{l(e.r(a.prefix,a.page,n.context,`close`),f()),o?.()},[o,n,a,f,l]);return(0,t.useEffect)(()=>{l(e.r(a.prefix,a.page,n.context,`view`),f())},[]),(0,r.jsx)(i.Alert,{appearance:d,title:n.title,onRemove:o?h:void 0,children:(0,r.jsxs)(i.Box,{display:`flex`,alignItems:`flex-start`,gap:`3`,flexWrap:`wrap`,flexDirection:`column`,children:[(0,r.jsx)(i.Box,{flex:`1 1 auto`,minWidth:`220px`,children:(0,r.jsx)(v,{content:n.message})}),(0,r.jsx)(i.Box,{display:`flex`,justifyContent:`flex-end`,marginTop:`2`,children:(0,r.jsx)(i.Button,{appearance:`primary`,onClick:m,children:n.cta.label})})]})})}var b={blue:{background:`#0050C3`,icon:`#FFFFFF`},white:{background:`#FFFFFF`,icon:`#0059D5`}};function x({data:n,trackingConfig:o,defaultVariant:c=`blue`,onClose:l,isMobile:u,onCtaClick:d}){let f=s(),{log:m}=e.n(),h=n.variant||c,g=b[h],[_,y]=(0,t.useState)(()=>window.innerWidth<750);(0,t.useEffect)(()=>{let e=()=>y(window.innerWidth<750);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let x=u??_,S=(0,t.useCallback)(()=>e.i({context:n.context,campaignId:n.campaignId,group:n.group,...n.metadata,...o.properties}),[n,o.properties]),C=(0,t.useCallback)(()=>{f(e.r(o.prefix,o.page,n.context,`click`),S()),d?d(n.cta):p(n.cta,m)},[n,o,S,f,d,m]),w=(0,t.useCallback)(()=>{f(e.r(o.prefix,o.page,n.context,`close`),S()),l?.()},[l,n,o,S,f]);(0,t.useEffect)(()=>{f(e.r(o.prefix,o.page,n.context,`view`),S())},[]);let T=(0,r.jsx)(i.Link,{as:`a`,textDecoration:`none`,onClick:C,"data-testid":`live-state-cta-link`,children:(0,r.jsx)(i.Text,{color:`primary-interactive`,fontSize:`base`,children:n.cta.label})});return(0,r.jsx)(i.Card,{children:(0,r.jsxs)(i.Box,{display:`flex`,flexDirection:`row`,justifyContent:`space-between`,children:[(0,r.jsxs)(i.Box,{display:`flex`,gap:`4`,alignItems:x?`flex-start`:`center`,paddingRight:`1-5`,children:[(0,r.jsx)(i.Box,{minWidth:`32px`,children:(0,r.jsx)(`div`,{style:{width:32,height:32,borderRadius:`35%`,borderColor:h===`white`?`#E7E7E7`:`transparent`,borderWidth:1,borderStyle:`solid`,background:g.background,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,r.jsx)(a.MoneyIcon,{style:{color:g.icon}})})}),(0,r.jsxs)(i.Box,{display:`grid`,gap:`2`,children:[(0,r.jsxs)(i.Box,{children:[(0,r.jsx)(v,{content:n.title,fontSize:`base`,color:`neutral-textHigh`}),(0,r.jsx)(v,{content:n.message,fontSize:`base`,color:`neutral-textLow`})]}),x&&T]})]}),(!x||l)&&(0,r.jsxs)(i.Box,{display:`flex`,flexDirection:x?`column`:`row`,alignItems:x?`flex-end`:`center`,gap:`2`,children:[!x&&T,l&&(0,r.jsx)(`button`,{type:`button`,"data-testid":`live-state-close-button`,"aria-label":`Fechar notificação`,onClick:w,style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,r.jsx)(i.Icon,{source:(0,r.jsx)(a.CloseIcon,{width:`18px`,height:`18px`}),color:`neutral-interactive`})})]})]})})}function S({data:t,loading:n,trackingConfig:i,allowedContexts:a,defaultVariant:o,isMobile:s,onCtaClick:c}){let{log:l,onNavigate:u}=e.n(),d=c??u,{isVisible:p,close:m}=f({context:t?.context??``,id:t?.campaignId,maxCloseTimes:t?.metadata?.maxCloseTimes,expiresIn:t?.metadata?.expiresIn});if(n||!t)return null;if(!t.context||!t.type||!t.title||!t.message||!t.cta?.label||!t.cta?.url||!t.cta?.type)return l(`warn`,`Invalid payload, missing required fields`,{data:t}),null;if(a&&!a.includes(t.context)||p===null||!p)return null;let h=t.closable?m:void 0;return t.type===`alert`||t.type===`warning`?(0,r.jsx)(y,{data:t,onClose:h,trackingConfig:i,onCtaClick:d}):t.type===`info`?(0,r.jsx)(x,{data:t,onClose:h,trackingConfig:i,defaultVariant:o,isMobile:s,onCtaClick:d}):(l(`warn`,`Unknown type: ${t.type}`,{data:t}),null)}exports.LIVE_STATE_STORAGE_KEY=c,exports.LiveStateAlert=y,exports.LiveStateInfo=x,exports.LiveStateProvider=e.t,exports.LiveStateRenderer=S,exports.handleCtaClick=p,exports.trackEvent=e.a,exports.useLiveState=o,exports.useTrackEvent=s;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as e, i as t, n, o as r, r as i, t as a } from "./LiveStateProvider-V3rVH59O.js";
1
+ import { a as e, i as t, n, o as r, r as i, t as a } from "./LiveStateProvider-AFY4pRGk.js";
2
2
  import { useCallback as o, useEffect as s, useState as c } from "react";
3
3
  import l from "swr";
4
4
  import { jsx as u, jsxs as d } from "react/jsx-runtime";
@@ -23,7 +23,7 @@ interface LiveStateContextValue {
23
23
  *
24
24
  * See examples/ directory for usage examples.
25
25
  */
26
- export declare function LiveStateProvider({ children, fetcher, analytics, onEvent, onLog, onNavigate, mockData, disabled, }: LiveStateProviderProps): import("react/jsx-runtime").JSX.Element;
26
+ export declare function LiveStateProvider({ children, fetcher, analytics, onEvent, onLog, onNavigate, mockData, disabled, cacheProvider, }: LiveStateProviderProps): import("react/jsx-runtime").JSX.Element;
27
27
  /**
28
28
  * useLiveStateContext
29
29
  *
@@ -1 +1 @@
1
- {"version":3,"file":"LiveStateProvider.d.ts","sourceRoot":"","sources":["../../../src/providers/LiveStateProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,sBAAsB,EACvB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE9D,UAAU,qBAAqB;IAC7B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACvE,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,SAAS,KAAK,IAAI,CAAC;IACtC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,GAAG,EAAE,QAAQ,CAAC;CACf;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,EAChC,QAAQ,EACR,OAAO,EACP,SAAS,EACT,OAAO,EACP,KAAK,EACL,UAAU,EACV,QAAQ,EACR,QAAgB,GACjB,EAAE,sBAAsB,2CA2BxB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,0BAQlC"}
1
+ {"version":3,"file":"LiveStateProvider.d.ts","sourceRoot":"","sources":["../../../src/providers/LiveStateProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,sBAAsB,EACvB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE9D,UAAU,qBAAqB;IAC7B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACvE,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,SAAS,KAAK,IAAI,CAAC;IACtC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,GAAG,EAAE,QAAQ,CAAC;CACf;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,EAChC,QAAQ,EACR,OAAO,EACP,SAAS,EACT,OAAO,EACP,KAAK,EACL,UAAU,EACV,QAAQ,EACR,QAAgB,EAChB,aAAa,GACd,EAAE,sBAAsB,2CA2BxB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,0BAQlC"}
@@ -227,6 +227,27 @@ export interface LiveStateProviderProps {
227
227
  * />
228
228
  */
229
229
  onNavigate?: (cta: CtaConfig) => void;
230
+ /**
231
+ * Shared SWR cache instance. When two or more `LiveStateProvider` instances
232
+ * receive the same `Map` reference, SWR deduplicates requests across them
233
+ * via `dedupingInterval` — a single network call serves all instances.
234
+ *
235
+ * When omitted, each provider gets its own isolated cache (current default
236
+ * behaviour), which is correct for independent providers with different
237
+ * fetchers or tokens.
238
+ *
239
+ * **Important:** pass the `Map` instance itself, not a factory function.
240
+ * The reference must be stable (declared outside the component).
241
+ *
242
+ * @example
243
+ * // Declare outside the component to keep a stable reference
244
+ * const sharedLiveStateCache = new Map();
245
+ *
246
+ * // Both providers share the same cache — one network request per cycle
247
+ * <LendingNotifications cacheProvider={sharedLiveStateCache} allowedContexts={['charge']} />
248
+ * <LendingNotifications cacheProvider={sharedLiveStateCache} allowedContexts={['awareness', 'cart']} />
249
+ */
250
+ cacheProvider?: Map<string, unknown>;
230
251
  }
231
252
  /**
232
253
  * LiveStateRenderer props
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAEtD;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mBAAmB;IACnB,KAAK,EAAE,MAAM,CAAC;IAEd,sBAAsB;IACtB,GAAG,EAAE,MAAM,CAAC;IAEZ;;;;;;;OAOG;IACH,IAAI,EAAE,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;IAE3C,+DAA+D;IAC/D,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAC;IAEhB,4BAA4B;IAC5B,IAAI,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;IAEnC,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAC;IAEd,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAC;IAEhB,mCAAmC;IACnC,GAAG,EAAE,SAAS,CAAC;IAEf,iDAAiD;IACjD,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,qBA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8BAA8B;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B,0CAA0C;IAC1C,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAElC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;;;;;;;;;;OAaG;IACH,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,SAAS,KAAK,IAAI,CAAC;CACvC"}
package/dist/testing.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./LiveStateProvider-ByK7lK2v.cjs`);let t=require(`react`);t=e.s(t,1);let n=require(`swr`),r=require(`react/jsx-runtime`);function i(e={}){return{context:`awareness`,type:`info`,title:`Mock notification`,message:`This is a mock notification for testing.`,cta:{label:`Learn more`,url:`/mock`,type:`internal`},...e}}var a=t.default.createContext(null);function o({children:i,liveState:o=null,isLoading:s=!1,isError:c=!1,onEvent:l}){let u=t.default.useCallback(async()=>{if(s)return new Promise(()=>{});if(c)throw Error(`Mock fetch error`);return o},[o,s,c]),d=t.default.useMemo(()=>e.o(void 0),[]),f=t.default.useMemo(()=>({fetcher:u,onEvent:l,disabled:!0,log:d}),[u,l,d]);return(0,r.jsx)(n.SWRConfig,{value:{provider:()=>new Map,dedupingInterval:0},children:(0,r.jsx)(a.Provider,{value:f,children:i})})}function s(e={}){return{liveState:e.liveState??null,isLoading:e.isLoading??!1,isError:e.isError??!1,error:e.error??null,refresh:e.refresh??(()=>Promise.resolve())}}exports.MockLiveStateProvider=o,exports.createMockLiveState=i,exports.mockUseLiveState=s,exports.useLiveStateContext=e.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./LiveStateProvider-L2Oxk6mo.cjs`);let t=require(`react`);t=e.s(t,1);let n=require(`swr`),r=require(`react/jsx-runtime`);function i(e={}){return{context:`awareness`,type:`info`,title:`Mock notification`,message:`This is a mock notification for testing.`,cta:{label:`Learn more`,url:`/mock`,type:`internal`},...e}}var a=t.default.createContext(null);function o({children:i,liveState:o=null,isLoading:s=!1,isError:c=!1,onEvent:l}){let u=t.default.useCallback(async()=>{if(s)return new Promise(()=>{});if(c)throw Error(`Mock fetch error`);return o},[o,s,c]),d=t.default.useMemo(()=>e.o(void 0),[]),f=t.default.useMemo(()=>({fetcher:u,onEvent:l,disabled:!0,log:d}),[u,l,d]);return(0,r.jsx)(n.SWRConfig,{value:{provider:()=>new Map,dedupingInterval:0},children:(0,r.jsx)(a.Provider,{value:f,children:i})})}function s(e={}){return{liveState:e.liveState??null,isLoading:e.isLoading??!1,isError:e.isError??!1,error:e.error??null,refresh:e.refresh??(()=>Promise.resolve())}}exports.MockLiveStateProvider=o,exports.createMockLiveState=i,exports.mockUseLiveState=s,exports.useLiveStateContext=e.n;
2
2
  //# sourceMappingURL=testing.cjs.map
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as e, o as t } from "./LiveStateProvider-V3rVH59O.js";
1
+ import { n as e, o as t } from "./LiveStateProvider-AFY4pRGk.js";
2
2
  import n from "react";
3
3
  import { SWRConfig as r } from "swr";
4
4
  import { jsx as i } from "react/jsx-runtime";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiendanube/live-state",
3
- "version": "1.0.0-beta.18",
3
+ "version": "1.0.0-beta.19",
4
4
  "description": "Generic React library for rendering live state notifications",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",