All files / src client.ts

97.46% Statements 77/79
95.29% Branches 81/85
95.45% Functions 21/22
97.46% Lines 77/79

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 2341x   1x                     1x 1x   1x 3x 6x 10x       1x 19x   11x 11x   1x   10x   7x 7x   1x   6x   1x       1x 39x                             1x               22x     22x 22x   22x   1x       22x   22x 1x             22x 2x   20x   20x 1x   19x 2x     19x     21x 1x     20x 20x                   18x       18x                   18x 17x 17x     16x 16x     1x   1x       18x                     18x     18x 18x   18x 16x 16x   16x     18x             5x   5x 5x 5x           3x 3x             1x             39x       16x     16x   16x 13x   13x 4x             12x 10x 10x            
import * as FingerprintJS from '@fingerprintjs/fingerprintjs-pro'
import { GetOptions, LoadOptions } from '@fingerprintjs/fingerprintjs-pro'
import {
  CacheKey,
  CacheManager,
  CacheStub,
  DEFAULT_CACHE_LIFE,
  ICache,
  InMemoryCache,
  LocalStorageCache,
  MAX_CACHE_LIFE,
  SessionStorageCache,
} from './cache'
import { CacheLocation, FpjsClientOptions, FpjsSpaResponse, VisitorData } from './global'
import * as packageInfo from '../package.json'
 
const cacheLocationBuilders: Record<CacheLocation, (prefix?: string) => ICache> = {
  [CacheLocation.Memory]: () => new InMemoryCache().enclosedCache,
  [CacheLocation.LocalStorage]: (prefix) => new LocalStorageCache(prefix),
  [CacheLocation.SessionStorage]: (prefix) => new SessionStorageCache(prefix),
  [CacheLocation.NoCache]: () => new CacheStub(),
}
 
const doesBrowserSupportCacheLocation = (cacheLocation: CacheLocation) => {
  switch (cacheLocation) {
    case CacheLocation.SessionStorage:
      try {
        window.sessionStorage.getItem('item')
      } catch (e) {
        return false
      }
      return true
    case CacheLocation.LocalStorage:
      try {
        window.localStorage.getItem('item')
      } catch (e) {
        return false
      }
      return true
    default:
      return true
  }
}
 
const cacheFactory = (location: CacheLocation) => {
  return cacheLocationBuilders[location]
}
 
export interface CustomAgent {
  load: (options: FingerprintJS.LoadOptions) => Promise<FingerprintJS.Agent>
}
 
export interface FpjsSpaOptions extends Omit<FpjsClientOptions, 'loadOptions'> {
  customAgent?: CustomAgent
  loadOptions?: FpjsClientOptions['loadOptions']
}
 
/**
 * FingerprintJS SDK for Single Page Applications
 */
export class FpjsClient {
  private cacheManager: CacheManager
  private readonly loadOptions: FingerprintJS.LoadOptions | undefined
  private agent: FingerprintJS.Agent
  private agentPromise: Promise<FingerprintJS.Agent> | null
  private readonly customAgent: CustomAgent | undefined
  readonly cacheLocation?: CacheLocation
 
  private inFlightRequests = new Map<string, Promise<VisitorData>>()
 
  constructor(options?: FpjsSpaOptions) {
    this.agentPromise = null
    this.customAgent = options?.customAgent
 
    this.agent = {
      get: () => {
        throw new Error("FPJSAgent hasn't loaded yet. Make sure to call the init() method first.")
      },
    }
 
    this.loadOptions = options?.loadOptions
 
    if (options?.cache && options?.cacheLocation) {
      console.warn(
        'Both `cache` and `cacheLocation` options have been specified in the FpjsClient configuration; ignoring `cacheLocation` and using `cache`.'
      )
    }
 
    let cache: ICache
 
    if (options?.cache) {
      cache = options.cache
    } else {
      this.cacheLocation = options?.cacheLocation || CacheLocation.SessionStorage
 
      if (!cacheFactory(this.cacheLocation)) {
        throw new Error(`Invalid cache location "${this.cacheLocation}"`)
      }
      if (!doesBrowserSupportCacheLocation(this.cacheLocation)) {
        this.cacheLocation = CacheLocation.Memory
      }
 
      cache = cacheFactory(this.cacheLocation)(options?.cachePrefix)
    }
 
    if (options?.cacheTimeInSeconds && options.cacheTimeInSeconds > MAX_CACHE_LIFE) {
      throw new Error(`Cache time cannot exceed 86400 seconds (24 hours)`)
    }
 
    const cacheTime = options?.cacheTimeInSeconds ?? DEFAULT_CACHE_LIFE
    this.cacheManager = new CacheManager(cache, cacheTime)
  }
 
  /**
   * Loads FPJS JS agent with certain settings and stores the instance in memory
   * [https://dev.fingerprint.com/docs/js-agent#agent-initialization]
   *
   * @param passedLoadOptions Additional load options to be passed to the agent, they will be merged with load options provided in the constructor.
   */
  public async init(passedLoadOptions?: Partial<LoadOptions>) {
    Iif (!this.loadOptions && !passedLoadOptions) {
      throw new TypeError('No load options provided')
    }
 
    const loadOptions: FingerprintJS.LoadOptions = {
      ...this.loadOptions!,
      ...passedLoadOptions!,
      integrationInfo: [
        ...(this.loadOptions?.integrationInfo || []),
        ...(passedLoadOptions?.integrationInfo || []),
        `fingerprintjs-pro-spa/${packageInfo.version}`,
      ],
    }
 
    if (!this.agentPromise) {
      const agentLoader = this.customAgent ?? FingerprintJS
      this.agentPromise = agentLoader
        .load(loadOptions)
        .then((agent) => {
          this.agent = agent
          return agent
        })
        .catch((error) => {
          this.agentPromise = null
 
          throw error
        })
    }
 
    return this.agentPromise
  }
 
  /**
   * Returns visitor identification data based on the request options
   * [https://dev.fingerprint.com/docs/js-agent#visitor-identification]
   *
   * @param options
   * @param ignoreCache if set to true a request to the API will be made even if the data is present in cache
   */
  public async getVisitorData<TExtended extends boolean>(
    options: GetOptions<TExtended> = {},
    ignoreCache = false
  ): Promise<FpjsSpaResponse<VisitorData<TExtended>>> {
    const cacheKey = FpjsClient.makeCacheKey(options)
    const key = cacheKey.toKey()
 
    if (!this.inFlightRequests.has(key)) {
      const promise = this._identify(options, ignoreCache).finally(() => {
        this.inFlightRequests.delete(key)
      })
      this.inFlightRequests.set(key, promise)
    }
 
    return (await this.inFlightRequests.get(key)) as FpjsSpaResponse<VisitorData<TExtended>>
  }
 
  /**
   * Returns cached visitor data based on the request options, or undefined if the data is not present in cache
   * */
  public async getVisitorDataFromCache<TExtended extends boolean>(
    options: GetOptions<TExtended> = {}
  ): Promise<FpjsSpaResponse<VisitorData<TExtended>> | undefined> {
    const cacheKey = FpjsClient.makeCacheKey(options)
    const cacheResult = await this.cacheManager.get(cacheKey)
    return cacheResult ? { ...cacheResult, cacheHit: true } : undefined
  }
 
  /**
   * Checks if request matching given options is present in cache
   * */
  public async isInCache(options: GetOptions<boolean> = {}) {
    return Boolean(await this.getVisitorDataFromCache(options))
  }
 
  /**
   * Clears visitor data from cache regardless of the cache implementation
   */
  public async clearCache() {
    await this.cacheManager.clearCache()
  }
 
  /**
   * Makes a CacheKey object from GetOptions
   */
  static makeCacheKey<TExtended extends boolean>(options: GetOptions<TExtended>) {
    return new CacheKey<TExtended>(options)
  }
 
  private async _identify<TExtended extends boolean>(
    options: GetOptions<TExtended>,
    ignoreCache = false
  ): Promise<FpjsSpaResponse<VisitorData<TExtended>>> {
    const key = FpjsClient.makeCacheKey(options)
 
    if (!ignoreCache) {
      const cacheResult = await this.cacheManager.get(key)
 
      if (cacheResult) {
        return {
          ...cacheResult,
          cacheHit: true,
        }
      }
    }
 
    const agentResult = (await this.agent.get(options)) as VisitorData<TExtended>
    await this.cacheManager.set(key, agentResult)
    return {
      ...agentResult,
      cacheHit: false,
    }
  }
}