All files / apps / web/src / lib firebase.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 3/3
100% Lines 9/9

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                2x         1x             3x   2x 2x 2x 1x     2x         2x    
import type { PublicConfig } from '@chattra/shared'
import { initializeApp } from 'firebase/app'
import { connectAuthEmulator, getAuth, type Auth } from 'firebase/auth'
 
// The one Firebase Auth instance of the SPA (design 4.1). Its settings come from /api/config, so
// one build serves every environment.
 
/** Port of the Auth emulator that `pnpm emulators` starts (firebase.json). */
export const AUTH_EMULATOR_PORT = 9099
 
// Same host name as the page: the emulator's iframe on another site (localhost vs 127.0.0.1) gets
// partitioned storage and the redirect result never comes back.
function getAuthEmulatorUrl(): string {
  return `http://${window.location.hostname}:${AUTH_EMULATOR_PORT}`
}
 
let auth: Auth | undefined
 
/** Starts Firebase Auth once; later calls return the same instance. */
export function initFirebaseAuth(config: PublicConfig): Auth {
  if (auth) return auth
 
  const { projectId, apiKey, authDomain, appId } = config.firebase
  auth = getAuth(initializeApp({ projectId, apiKey, authDomain, appId }))
  if (config.environment === 'local') {
    connectAuthEmulator(auth, getAuthEmulatorUrl(), { disableWarnings: true })
  }
 
  return auth
}
 
/** Test only: forget the instance. */
export function resetFirebaseAuth(): void {
  auth = undefined
}