All files / src detect-env.ts

92.3% Statements 24/26
86.66% Branches 13/15
100% Functions 8/8
91.3% Lines 21/23

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 895x                       76x 19x       38x 37x   37x 2x       17x               17x             15x               19x 19x 18x               2x           19x 19x 2x           17x 2x         15x 15x                  
import { Env, type EnvDetails } from './env.types'
 
export interface DetectEnvContext {
  classRenderReceivesAnyArguments: boolean
}
 
export interface DetectEnvParams {
  context: DetectEnvContext
}
 
type EnvCheckStrategy = () => unknown
 
function runEnvChecks(...strategies: EnvCheckStrategy[]) {
  Iif (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
}
 
/**
 * Checks if user is using react.
 * */
function isReact(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(
    () => 'next' in window && Boolean((window as { next?: unknown }).next),
    () => document.querySelector('script[id=__NEXT_DATA__]')
  )
}
 
/**
 * Returns next version currently used by user.
 * */
function getNextVersion() {
  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,
    }
  }
 
  if (isReact(context)) {
    return {
      name: Env.React,
    }
  }
 
  return {
    name: Env.Unknown,
  }
}