-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboolean.ts
More file actions
57 lines (55 loc) · 2 KB
/
boolean.ts
File metadata and controls
57 lines (55 loc) · 2 KB
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
/**
* @fileoverview `envAsBoolean` — coerce an env-var-shaped value into
* a boolean. Accepts a back-compat positional `defaultValue` or an
* options bag (with `trim`). Truthy vocabulary is `'1'` / `'true'` /
* `'yes'` case-insensitively after optional trim.
*/
import type { EnvAsBooleanOptions } from './types'
/**
* Convert an environment variable value to a boolean.
*
* Back-compat overload: passing a bare boolean as the second argument is
* equivalent to `{ defaultValue: B }`.
*
* @param value - The value to convert
* @param defaultValueOrOptions - Default (boolean) or options object
* @returns `true` if value is '1', 'true', or 'yes' (case-insensitive), `false` otherwise
*
* @example
* ```typescript
* import { envAsBoolean } from '@socketsecurity/lib/env/boolean'
*
* envAsBoolean('true') // true
* envAsBoolean('1') // true
* envAsBoolean('yes') // true
* envAsBoolean(' true ') // true (trimmed)
* envAsBoolean(' true ', { trim: false }) // false (strict)
* envAsBoolean(undefined) // false
* envAsBoolean(undefined, true) // true (legacy positional default)
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function envAsBoolean(
value: unknown,
defaultValueOrOptions: boolean | EnvAsBooleanOptions | undefined = false,
): boolean {
// `?? {}` arm fires only when caller passes undefined explicitly.
/* c8 ignore next 4 */
const opts: EnvAsBooleanOptions =
typeof defaultValueOrOptions === 'boolean'
? { defaultValue: defaultValueOrOptions }
: (defaultValueOrOptions ?? {})
const { defaultValue = false, trim = true } = opts
if (typeof value === 'string') {
const candidate = trim ? value.trim() : value
if (!candidate) {
return !!defaultValue
}
const lower = candidate.toLowerCase()
return lower === '1' || lower === 'true' || lower === 'yes'
}
if (value === null || value === undefined) {
return !!defaultValue
}
return !!value
}