import { isNonEmptyString } from './validation'; /** * Interface for the Klaviyo Auth Token API. * * Personalized In-App Forms require the SDK to present a user-identifying JWT to * the Klaviyo backend. The React Native SDK is a thin wrapper: the underlying * native iOS and Android SDKs own all token state management (caching, proactive * refresh, timeouts when waiting for a token, WebView injection, and all * token-related logging). The wrapper's sole responsibility is to bridge the * host's JS-side provider to the native SDK. */ export interface KlaviyoAuthTokenApi { /** * Registers a provider that the native SDK invokes when it needs to acquire or * refresh an authentication token (JWT) for the current end-user. * * The provider is an `async` function returning the current end-user's JWT, by * whatever mechanism the host application uses to obtain a fresh token * (e.g. calling its auth server or exchanging an OAuth refresh token). Read the * current user fresh on each invocation rather than capturing identity at * registration. Fetch a fresh JWT each time; do not cache tokens in the * provider. The native SDK manages token caching and refresh. * * Register once and keep the provider registered across profile changes. * On logout, clear the SDK profile with `resetProfile()`. Apply a timeout to * every network call: the SDK does not time out or abort the provider * itself. A provider that never settles blocks later token fetches until * you register, unregister, or reset the profile. * * Calling this replaces any previously-registered provider. The call itself is * synchronous (fire-and-forget) and returns `void`, consistent with other * configuration methods such as {@link KlaviyoProfileApi.setProfile} and * {@link KlaviyoFormsApi.registerForInAppForms}. * * @param provider Async function that resolves with the current end-user's JWT. */ registerAuthTokenProvider(provider: AuthTokenProvider): void; /** * Detaches a previously-registered auth token provider to turn personalization * off. This is not a logout; use `resetProfile()` to clear the SDK profile. * * Forwards to the native SDK, which clears the provider reference and tears * down its own token state (cached token, scheduled refresh, and the native * side of any in-flight fetch). A host `provider()` call that is already * running is not aborted — it runs to completion and its late response is * ignored. Re-registering after unregister works normally. A form that is * already open keeps its token until it expires, whether you call * `resetProfile()` or `unregisterAuthTokenProvider()`. */ unregisterAuthTokenProvider(): void; } /** * Host-provided function that supplies an auth token (JWT) to the SDK. * * Invoked by the native SDK when it needs a token. Returns a `Promise` that * resolves with the current end-user's JWT, or rejects if a token cannot be * obtained. * * **Connectivity failures:** if the provider rejects because the device is * offline, the SDK can wait for connectivity to return and retry — but only * when it can recognize the failure as a network error. The bridge auto-detects * React Native's `fetch` network failure (`TypeError: Network request failed`) * and `AbortError`. If the host uses a different HTTP client, it can opt in * explicitly by rejecting with an error carrying `isConnectivityError === true`: * * ```ts * throw Object.assign(new Error('offline'), { isConnectivityError: true }); * ``` * * All other rejections are treated as non-connectivity failures (no * connectivity-driven retry), matching the native SDKs' error classification. */ export type AuthTokenProvider = () => Promise; /** * Name of the native-to-JS event emitted over `NativeEventEmitter` when the * native SDK requests an auth token from the wrapper-provided provider. */ export const AUTH_TOKEN_REQUESTED_EVENT = 'klaviyo:authTokenRequested'; /** * Payload of an {@link AUTH_TOKEN_REQUESTED_EVENT} event. * * The `id` correlation identifier is generated on the native side and must be * echoed back via `respondToAuthTokenRequest` so the native SDK can resolve the * awaiting provider invocation. */ export interface AuthTokenRequestedEvent { /** Correlation ID identifying this token request. */ id: string; } /** * Parses a raw native event payload into a validated {@link AuthTokenRequestedEvent}. * * Returns `null` and logs a warning if the required `id` correlation field is * missing or empty. Never logs token contents (the request payload carries only * the correlation ID, not a token). * * @param data Raw event data from the native bridge * @returns A validated AuthTokenRequestedEvent, or null if the payload is invalid */ export function parseAuthTokenRequestedEvent( data: Record ): AuthTokenRequestedEvent | null { const { id } = data; if (!isNonEmptyString(id)) { console.warn( `[Klaviyo] Ignoring auth token request with invalid id: ${JSON.stringify(id)}` ); return null; } return { id }; } /** * Result of classifying a provider rejection before it is sent back to native. */ export interface ClassifiedProviderError { /** Human-readable failure message (never a token). */ message: string; /** * Whether the failure is a connectivity error. When `true`, the native bridge * reconstitutes a typed network error (`URLError` on iOS, `IOException` on * Android) that the SDK's connectivity-driven refresh retry recognizes. */ isConnectivityError: boolean; } /** * Classifies a rejected {@link AuthTokenProvider} into a message plus a * connectivity flag for the native bridge. * * Classification order: * - An explicit boolean `isConnectivityError` marker on the error is * authoritative in both directions — `true` forces connectivity, `false` * opts out — regardless of the heuristics below (HTTP-client-agnostic). * - Otherwise, well-known React Native network-failure signatures are * auto-detected: an `AbortError`, or `fetch` throwing * `TypeError: Network request failed`. * - Everything else is a non-connectivity failure. * * Token contents are never part of a rejection and are never logged. */ export function classifyProviderError(error: unknown): ClassifiedProviderError { // Raw host text is used ONLY for internal connectivity auto-detection below; // it is never returned/logged/forwarded (it could contain the JWT). const rawMessage = error instanceof Error ? error.message : String(error); // The reported message is redacted to the error's type — safe to log and // forward to native, and still useful for diagnosis. const message = redactErrorType(error); // An explicit boolean marker wins over the auto-detect heuristics. if (typeof error === 'object' && error !== null) { const marker = (error as { isConnectivityError?: unknown }) .isConnectivityError; if (typeof marker === 'boolean') { return { message, isConnectivityError: marker }; } } const isAbortError = typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError'; // React Native's `fetch` throws `TypeError: Network request failed` when the // request cannot reach the network. const isFetchNetworkFailure = error instanceof TypeError && /network request failed/i.test(rawMessage); return { message, isConnectivityError: isAbortError || isFetchNetworkFailure, }; } /** * Returns a safe, non-sensitive descriptor of an error: its runtime type name * (e.g. `Error`, `TypeError`, or a custom class name), or `typeof` for * non-object rejections. Never returns host-controlled text such as * `error.message`, which could contain the JWT or other credentials. */ function redactErrorType(error: unknown): string { if (typeof error === 'object' && error !== null) { return error.constructor?.name ?? 'Object'; } return typeof error; }