All files / src/components fpjs-provider.tsx

88.52% Statements 54/61
69.23% Branches 9/13
83.33% Functions 10/12
91.22% Lines 52/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 1643x 3x 3x 3x 3x 3x 3x     3x                                                                   3x 14x   14x                           14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x   14x 12x                   14x 12x   12x 12x   12x     12x               12x   12x   12x     14x 10x       16x 8x 4x                   10x     14x 10x 10x   20x   10x         14x           14x 12x           14x     12x 12x       14x    
import { PropsWithChildren, useCallback, useEffect, useMemo, useRef } from 'react'
import { FpjsContext } from '../fpjs-context'
import { FpjsClient, FpjsClientOptions, FingerprintJSPro } from '@fingerprintjs/fingerprintjs-pro-spa'
import * as packageInfo from '../../package.json'
import { isSSR } from '../ssr'
import { waitUntil } from '../utils/wait-until'
import { WithEnvironment } from './with-environment'
import type { EnvDetails } from '../env.types'
 
const pkgName = packageInfo.name.split('/')[1]
 
export interface CustomAgent {
  load: (options: FingerprintJSPro.LoadOptions) => Promise<FingerprintJSPro.Agent>
}
export interface FpjsProviderOptions extends FpjsClientOptions {
  /**
   * If set to `true`, will force FpjsClient to be rebuilt with the new options. Should be used with caution
   * since it can be triggered too often (e.g. on every render) and negatively affect performance of the JS agent.
   */
  forceRebuild?: boolean
  customAgent?: CustomAgent
}
 
/**
 * @example
 * ```jsx
 * <FpjsProvider
 *   loadOptions = {{
 *     apiKey: "<your-fpjs-public-api-key>"
 *   }}
 *   cacheTime={60 * 10}
 *   cacheLocation={CacheLocation.LocalStorage}
 * >
 *   <MyApp />
 * </FpjsProvider>
 * ```
 *
 * Provides the FpjsContext to its child components.
 *
 * @privateRemarks
 * This is just a wrapper around the actual provider.
 * For the implementation, see `ProviderWithEnv` component.
 */
export function FpjsProvider<T extends boolean>(props: PropsWithChildren<FpjsProviderOptions>) {
  const propsWithEnv = props as PropsWithChildren<ProviderWithEnvProps>
 
  return (
    <WithEnvironment>
      <ProviderWithEnv<T> {...propsWithEnv} />
    </WithEnvironment>
  )
}
 
interface ProviderWithEnvProps extends FpjsProviderOptions {
  /**
   * Contains details about the env we're currently running in (e.g. framework, version)
   */
  env: EnvDetails
}
 
function ProviderWithEnv<TExtended extends boolean>({
  children,
  forceRebuild,
  cache,
  cacheTimeInSeconds,
  cachePrefix,
  cacheLocation,
  customAgent,
  loadOptions,
  env,
}: PropsWithChildren<ProviderWithEnvProps>) {
  const clientRef = useRef<FpjsClient>()
  const clientInitPromiseRef = useRef<Promise<unknown>>()
 
  const clientOptions = useMemo(() => {
    return {
      cache,
      cacheTimeInSeconds,
      cachePrefix,
      cacheLocation,
      customAgent,
      loadOptions,
    }
  }, [loadOptions, cache, cacheTimeInSeconds, cachePrefix, cacheLocation, customAgent])
 
  const createClient = useCallback(() => {
    let integrationInfo = `${pkgName}/${packageInfo.version}`
 
    if (env) {
      const envInfo = env.version ? `${env.name}/${env.version}` : env.name
 
      integrationInfo += `/${envInfo}`
    }
 
    const parsedClientOptions = {
      ...clientOptions,
      loadOptions: {
        ...loadOptions,
        integrationInfo: [...(loadOptions.integrationInfo || []), integrationInfo],
      },
    }
 
    const createdClient = new FpjsClient(parsedClientOptions)
 
    clientInitPromiseRef.current = createdClient.init()
 
    return createdClient
  }, [clientOptions, env, loadOptions])
 
  const getClient = useCallback(async () => {
    Iif (isSSR()) {
      throw new Error('FpjsProvider client cannot be used in SSR')
    }
 
    if (!clientRef.current) {
      await waitUntil({
        checkCondition: () => Boolean(clientRef.current),
      }).catch(async () => {
        /**
         * We did timeout waiting for ideal condition to create client (eg: env detection)
         * Attempt to create client now, potentially without some additional information that might be useful but are not required.
         * */
        createClient()
      })
    }
 
    return clientRef.current!
  }, [createClient])
 
  const getVisitorData = useCallback(
    async (options?: FingerprintJSPro.GetOptions<TExtended>, ignoreCache?: boolean) => {
      const client = await getClient()
 
      await clientInitPromiseRef.current
 
      return client.getVisitorData<TExtended>(options, ignoreCache)
    },
    [getClient]
  )
 
  const clearCache = useCallback(async () => {
    const client = await getClient()
 
    await client.clearCache()
  }, [getClient])
 
  const contextValue = useMemo(() => {
    return {
      clearCache,
      getVisitorData,
    }
  }, [clearCache, getVisitorData])
 
  useEffect(() => {
    // By default, the client is always initialized once during the first render and won't be updated
    // if the configuration changes. Use `forceRebuilt` flag to disable this behaviour.
    if (!clientRef.current || forceRebuild) {
      clientRef.current = createClient()
    }
  }, [forceRebuild, clientOptions, createClient])
 
  return <FpjsContext.Provider value={contextValue}>{children}</FpjsContext.Provider>
}