All files / src/lib/dsn env.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 2/2
100% Lines 13/13

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                        161x             161x                       161x 805x                                 66x   66x 66x 331x 331x 21x 21x 17x         49x    
/**
 * Environment Variable Detection
 *
 * Detects DSN from SENTRY_DSN environment variable.
 * This is the highest priority source.
 */
 
import { getEnv } from "../env.js";
import { createDetectedDsn } from "./parser.js";
import type { DetectedDsn } from "./types.js";
 
/** Environment variable name for Sentry DSN */
export const SENTRY_DSN_ENV = "SENTRY_DSN";
 
/**
 * Framework-specific env var prefixes that expose values to client-side code.
 * Used to build both the runtime env var checklist and the .env file regex
 * so that both detection paths match the same set of variable names.
 */
export const FRAMEWORK_ENV_PREFIXES = [
  "NEXT_PUBLIC_",
  "REACT_APP_",
  "VITE_",
  "EXPO_PUBLIC_",
  "NUXT_PUBLIC_",
] as const;
 
/**
 * Framework-prefixed env var names that commonly hold a Sentry DSN.
 * Checked in order after `SENTRY_DSN` (canonical name has priority).
 */
const FRAMEWORK_DSN_VARS = FRAMEWORK_ENV_PREFIXES.map(
  (prefix) => `${prefix}SENTRY_DSN`
);
 
/**
 * Detect DSN from environment variables.
 *
 * Checks `SENTRY_DSN` first (canonical), then common framework-prefixed
 * variants (NEXT_PUBLIC_SENTRY_DSN, REACT_APP_SENTRY_DSN, etc.).
 *
 * @returns Detected DSN or null if not set/invalid
 *
 * @example
 * // With SENTRY_DSN=https://key@o123.ingest.sentry.io/456
 * const dsn = detectFromEnv();
 * // { raw: "...", source: "env", projectId: "456", ... }
 */
export function detectFromEnv(): DetectedDsn | null {
  const env = getEnv();
 
  const allVars = [SENTRY_DSN_ENV, ...FRAMEWORK_DSN_VARS];
  for (const varName of allVars) {
    const value = env[varName];
    if (value) {
      const detected = createDetectedDsn(value, "env", varName);
      if (detected) {
        return detected;
      }
    }
  }
 
  return null;
}