All files / src/utils turnstile.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 5/5
100% Lines 14/14

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                                                        4x   4x     6x 5x 4x 4x 4x 4x 2x 4x 4x     2x 2x   5x    
// @implements UC-AUTH-009.1
/**
 * Loads Cloudflare Turnstile, the sign-up CAPTCHA, once per page. The token it
 * gives is checked by the API's Pre Sign-up trigger (flows-api utils/turnstile.js).
 */
export interface TurnstileRenderOptions {
  sitekey: string
  action: string
  language: string
  theme: 'auto' | 'light' | 'dark'
  callback: (token: string) => void
  'expired-callback': () => void
  'error-callback': () => void
}
 
export interface TurnstileApi {
  render: (element: HTMLElement, options: TurnstileRenderOptions) => string
  reset: (widgetId: string) => void
  remove: (widgetId: string) => void
}
 
declare global {
  interface Window {
    turnstile?: TurnstileApi
  }
}
 
export const TURNSTILE_SCRIPT_URL =
  'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
 
let loading: Promise<TurnstileApi> | null = null
 
export function loadTurnstile(): Promise<TurnstileApi> {
  if (window.turnstile) return Promise.resolve(window.turnstile)
  loading ??= new Promise<TurnstileApi>((resolve, reject) => {
    const script = document.createElement('script')
    script.src = TURNSTILE_SCRIPT_URL
    script.async = true
    script.onload = () =>
      window.turnstile ? resolve(window.turnstile) : reject(new Error('Turnstile not loaded'))
    script.onerror = () => reject(new Error('Turnstile script failed to load'))
    document.head.appendChild(script)
  }).catch((error) => {
    // A later sign-up page may try again
    loading = null
    throw error
  })
  return loading
}