Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ Each validation function accepts an (optional) object with the following attribu
helper (which is wrapped around a `devDefault` and therefore can't coexist with a separate
dev value), `testDefault` can be combined with `default` and `devDefault` to provide
distinct values for production, development, and test.
- `warning` - A message that is logged (without failing) when the env var is not set and a
fallback value (`default`, `devDefault`, or `testDefault`) is used. Combine with
`default: undefined` to allow the program to run without the env var while still
surfacing a warning.
- `desc` - A string that describes the env var.
- `example` - An example value for the env var.
- `docs` - A URL that leads to more detailed documentation about the env var.
Expand Down
45 changes: 25 additions & 20 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export function getSanitizedEnv<S>(
const cleanedEnv = {} as SpecsOutput<S>
const castedSpecs = specs as unknown as Record<keyof S, ValidatorSpec<unknown>>
const errors = {} as Record<keyof S, Error>
const warnings = {} as Record<keyof S, string>
const varKeys = Object.keys(castedSpecs) as Array<keyof S>
const rawNodeEnv = readRawEnvValue(environment, 'NODE_ENV')

Expand All @@ -78,26 +79,26 @@ export function getSanitizedEnv<S>(
// Use testDefault only when NODE_ENV is 'test'. Takes priority over devDefault and default.
if (rawNodeEnv === 'test' && Object.hasOwn(spec, 'testDefault')) {
cleanedEnv[k] = spec.testDefault
continue
} else {
// Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production'
const usingDevDefault =
rawNodeEnv && rawNodeEnv !== 'production' && Object.hasOwn(spec, 'devDefault')

if (usingDevDefault) {
cleanedEnv[k] = spec.devDefault
} else if ('default' in spec) {
cleanedEnv[k] = spec.default
} else {
// Throw error when no default value is provided
cleanedEnv[k] = undefined
throw new EnvMissingError(formatSpecDescription(spec))
}
}

// Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production'
const usingDevDefault =
rawNodeEnv && rawNodeEnv !== 'production' && Object.hasOwn(spec, 'devDefault')

if (usingDevDefault) {
cleanedEnv[k] = spec.devDefault
continue
}

if ('default' in spec) {
cleanedEnv[k] = spec.default
continue
}

// Throw error when no default value is provided
cleanedEnv[k] = undefined
throw new EnvMissingError(formatSpecDescription(spec))
// A `warning` message is surfaced (without failing) whenever the env var was
// not set and a fallback value was used
if (spec.warning) warnings[k] = spec.warning
continue
}

cleanedEnv[k] = validateVar({ name: k as string, spec, rawValue })
Expand All @@ -122,7 +123,11 @@ export function getSanitizedEnv<S>(
}
}

const reporter = options?.reporter || defaultReporter
reporter({ errors, env: cleanedEnv })
// With `reporter: null`, errors are thrown instead of reported; in that case the
// caller opts out of all reporting, including warnings
if (options?.reporter !== null) {
const reporter = options?.reporter || defaultReporter
reporter({ errors, warnings, env: cleanedEnv })
}
return cleanedEnv
}
12 changes: 11 additions & 1 deletion src/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,19 @@ export const envalidErrorFormatter = <T = any>(
}

export const defaultReporter = <T = any>(
{ errors = {} }: ReporterOptions<T>,
{ errors = {}, warnings = {} }: ReporterOptions<T>,
{ onError, logger }: ExtraOptions<T> = { logger: defaultLogger },
) => {
// Warnings are informational, and never affect the exit behavior
const warningsOutput = Object.entries(warnings).map(
([k, message]) => ` ${colors.blue(k)}: ${message}`,
)
if (warningsOutput.length) {
warningsOutput.sort()
warningsOutput.unshift(` ${colors.yellow('Warnings')}:`)
logger([RULE, warningsOutput.join('\n'), RULE].join('\n'))
}

if (!Object.keys(errors).length) return

envalidErrorFormatter(errors, logger)
Expand Down
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ export interface Spec<T> {
*/
testDefault?: NonNullable<T> | undefined

/**
* A message that is logged (without failing) when the env var is not set and a
* fallback value (`default`, `devDefault`, or `testDefault`) is used.
* Combine with `default: undefined` to allow the program to run without the env
* var while still surfacing a warning.
*/
warning?: string

/**
* A function (env -> boolean) that allows an env var to be required only when certain
* conditions are met with the rest of the env object. Use With default: undefined.
Expand Down Expand Up @@ -149,6 +157,12 @@ export interface CleanedEnvAccessors {

export interface ReporterOptions<T> {
errors: Partial<Record<keyof T, Error>>
/**
* Warning messages for env vars that were not set and had a fallback value
* (`default`, `devDefault`, or `testDefault`) used. Only populated for specs that
* include a `warning` message.
*/
warnings?: Partial<Record<keyof T, string>>
env: unknown
}

Expand Down
87 changes: 87 additions & 0 deletions tests/reporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,93 @@ describe('default reporter', () => {
})
})

describe('default reporter with warnings', () => {
let logger: MockedFunction<any>
let exitSpy: any = null

beforeEach(() => {
logger = vi.fn()
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any)
})

afterEach(() => {
exitSpy?.mockRestore()
})

test('prints warnings without exiting when there are no errors', () => {
defaultReporter(
{
errors: {},
warnings: { FOO: 'FOO is not set' },
env: {},
},
{ logger },
)

expect(logger).toHaveBeenCalledTimes(1)
const output = logger?.mock?.calls?.[0]?.[0]
expect(output).toMatch(/Warnings\S*:/)
expect(output).toMatch(/FOO\S*: FOO is not set/)
expect(output).not.toMatch(/Exiting with error code 1/)
expect(exitSpy).toHaveBeenCalledTimes(0)
})

test('prints both warnings and errors, and still exits when errors exist', () => {
defaultReporter(
{
errors: { FOO: new EnvMissingError() },
warnings: { BAR: 'BAR is not set' },
env: {},
},
{ logger },
)

expect(logger).toHaveBeenCalledTimes(3)

const warningsOutput = logger?.mock?.calls?.[0]?.[0]
expect(warningsOutput).toMatch(/Warnings\S*:/)
expect(warningsOutput).toMatch(/BAR\S*: BAR is not set/)

const errorsOutput = logger?.mock?.calls?.[1]?.[0]
expect(errorsOutput).toMatch(/Missing\S+ environment variables:/)
expect(errorsOutput).not.toMatch(/Warnings\S*:/)

const exitOutput = logger?.mock?.calls?.[2]?.[0]
expect(exitOutput).toMatch(/Exiting with error code 1/)

expect(exitSpy).toHaveBeenCalledTimes(1)
expect(exitSpy).toHaveBeenCalledWith(1)
})

test('sorts multiple warnings', () => {
defaultReporter(
{
errors: {},
warnings: { ZEBRA: 'z', ALPACA: 'a' },
env: {},
},
{ logger },
)

const output = logger?.mock?.calls?.[0]?.[0]
expect(output.indexOf(': a')).toBeGreaterThan(-1)
expect(output.indexOf(': a')).toBeLessThan(output.indexOf(': z'))
})

test('does nothing when there are no errors or warnings', () => {
defaultReporter(
{
errors: {},
warnings: {},
env: { FOO: 'great success' },
},
{ logger },
)
expect(logger).toHaveBeenCalledTimes(0)
expect(exitSpy).toHaveBeenCalledTimes(0)
})
})

describe('envalidErrorFormatter', () => {
let logger: MockedFunction<any>

Expand Down
6 changes: 6 additions & 0 deletions tests/requiredWhen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe('requiredWhen', () => {
id: undefined,
},
errors: {},
warnings: {},
})
})

Expand All @@ -51,6 +52,7 @@ describe('requiredWhen', () => {
id: undefined,
},
errors: {},
warnings: {},
})

cleanEnv(
Expand All @@ -70,6 +72,7 @@ describe('requiredWhen', () => {
autoExtractId: undefined,
},
errors: {},
warnings: {},
})
})

Expand Down Expand Up @@ -102,6 +105,7 @@ describe('requiredWhen', () => {
),
),
},
warnings: {},
})
})

Expand All @@ -126,6 +130,7 @@ describe('requiredWhen', () => {
id: 123,
},
errors: {},
warnings: {},
})
})

Expand All @@ -152,6 +157,7 @@ describe('requiredWhen', () => {
errors: {
id: new EnvError(`Invalid number input: "abc"`),
},
warnings: {},
})
})
})
Loading
Loading