Files
ipal-kit/src/modules/env/assertEnv.ts
T

138 lines
4.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Zero-dependency environment validation. The plugin deliberately does NOT pull
* in zod — forcing a validation library on every project would be a dependency
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
* tiny validator that does the one thing we need: check the vars a deploy needs
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
*/
export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url'
export type EnvRule = {
/** Shown in the error to tell the deployer what the var is for. */
description?: string
/** Shape check applied when a value is present. Default 'string' (non-empty). */
kind?: EnvKind
/** Variable name, e.g. 'DATABASE_URI'. */
name: string
/** Allowed values (e.g. NODE_ENV). Checked when a value is present. */
oneOf?: readonly string[]
/** Default true. When false, the var is only validated if present. */
required?: boolean
/** Custom check: return true if OK, or an error message string. */
validate?: (value: string) => string | true
}
export type AssertEnvOptions = {
/** Source of values. Default process.env. */
env?: Record<string, string | undefined>
/** Error prefix. Default '[ipal]'. */
label?: string
}
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Validate one present value against its rule. Returns an error message or null. */
function checkValue(rule: EnvRule, value: string): null | string {
const { name, kind = 'string', oneOf } = rule
if (oneOf && !oneOf.includes(value)) {
return `${name} must be one of: ${oneOf.join(', ')} (got "${value}")`
}
switch (kind) {
case 'boolean':
if (!/^(?:true|false|1|0|yes|no)$/i.test(value)) {
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`
}
break
case 'email':
if (!EMAIL_RE.test(value)) {return `${name} must be an e-mail address (got "${value}")`}
break
case 'number':
if (!Number.isFinite(Number(value))) {return `${name} must be a number (got "${value}")`}
break
case 'port': {
const n = Number(value)
if (!Number.isInteger(n) || n < 1 || n > 65535) {
return `${name} must be a port 1–65535 (got "${value}")`
}
break
}
case 'url':
try {
new URL(value)
} catch {
return `${name} must be a valid URL (got "${value}")`
}
break
case 'string':
default:
break
}
if (rule.validate) {
const res = rule.validate(value)
if (res !== true) {return typeof res === 'string' ? res : `${name} is invalid`}
}
return null
}
/**
* Validates the given rules against the environment and THROWS a single,
* aggregated error listing every problem at once (not just the first). Call it
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
*
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
*
* or with hand-written rules:
*
* assertEnv([
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
* ])
*
* Runs server-side only (reads process.env) — never import it into a client
* component.
*/
export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {
const env = options.env ?? process.env
const label = options.label ?? '[ipal]'
const problems: string[] = []
for (const rule of rules) {
const raw = env[rule.name]
const value = typeof raw === 'string' ? raw.trim() : ''
const required = rule.required !== false
if (!value) {
if (required) {
problems.push(
`${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`,
)
}
continue // optional + absent → nothing to check
}
const err = checkValue(rule, value)
if (err) {
problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`)
}
}
if (problems.length === 0) {return}
const message =
`${label} Environment validation failed (${problems.length} ` +
`problem${problems.length === 1 ? '' : 's'}):\n` +
problems.map((p) => ` • ${p}`).join('\n') +
`\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`
throw new Error(message)
}