All files / src detect-env.ts

100% Statements 17/17
100% Branches 10/10
100% Functions 7/7
100% Lines 17/17

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                              41x 1x     40x 78x   78x 3x       37x               38x               41x   40x 38x                 3x             41x 3x           38x 3x         35x          
import { version as reactVersion } from 'react'
 
import { Env, type EnvDetails } from './env.types'
 
export interface DetectEnvContext {
  classRenderReceivesAnyArguments: boolean
}
 
export interface DetectEnvParams {
  context: DetectEnvContext
}
 
type EnvCheckStrategy = () => boolean
 
function runEnvChecks(...strategies: EnvCheckStrategy[]) {
  if (typeof window === 'undefined') {
    return false
  }
 
  for (const strategy of strategies) {
    const result = strategy()
 
    if (result) {
      return true
    }
  }
 
  return false
}
 
/**
 * Runs checks that determine if user is using preact.
 * So far they are not ideal, as there is no consistent way to detect preact.
 * */
function isPreact(context: DetectEnvContext) {
  return context.classRenderReceivesAnyArguments
}
 
/**
 * Runs checks that determine if user is using next.
 * Those checks should have almost 100% accuracy.
 * */
function isNext() {
  return runEnvChecks(
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    () => 'next' in window && Boolean((window as { next?: unknown }).next),
    () => document.querySelector('script[id=__NEXT_DATA__]') !== null
  )
}
 
/**
 * Returns next version currently used by user.
 * */
function getNextVersion() {
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
  return (window as { next?: { version?: string } }).next?.version
}
 
/**
 * Attempts to determine user environment.
 * */
export function detectEnvironment({ context }: DetectEnvParams): EnvDetails {
  if (isNext()) {
    return {
      name: Env.Next,
      version: getNextVersion(),
    }
  }
 
  if (isPreact(context)) {
    return {
      name: Env.Preact,
    }
  }
 
  return {
    name: Env.React,
    version: reactVersion,
  }
}