From ce5c0e53241c131f7787844c21fc69e898aa5c17 Mon Sep 17 00:00:00 2001 From: "Simen A. W. Olsen" Date: Wed, 5 Apr 2023 03:40:55 +0200 Subject: [PATCH] Allow support for extra inspectables (#206) --- src/middleware.ts | 15 ++++++++++++--- src/types.ts | 9 +++++++++ tests/middleware.test.ts | 13 ++++++++++++- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index d90535c..2287e21 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,6 +1,11 @@ -import { CleanedEnvAccessors } from './types' +import { CleanedEnvAccessors, StrictProxyMiddlewareOptions } from './types' -export const strictProxyMiddleware = (envObj: T, rawEnv: unknown) => { +export const strictProxyMiddleware = ( + envObj: T, + rawEnv: unknown, + options: StrictProxyMiddlewareOptions = {}, +) => { + const { extraInspectables = [] } = options const inspectables = [ 'length', 'inspect', @@ -29,7 +34,11 @@ export const strictProxyMiddleware = (envObj: T, rawEnv: unkno // proxy that throws crashes the entire process. This permits access on // the necessary properties for `console.log(envObj)`, `envObj.length`, // `envObj.hasOwnProperty('string')` to work. - if (inspectables.includes(name) || inspectSymbolStrings.includes(name.toString())) { + if ( + inspectables.includes(name) || + inspectSymbolStrings.includes(name.toString()) || + extraInspectables.includes(name) + ) { // @ts-expect-error TS doesn't like symbol types as indexers return target[name] } diff --git a/src/types.ts b/src/types.ts index ebfe6c5..291adc5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -136,3 +136,12 @@ export interface CleanOptions { */ reporter?: ((opts: ReporterOptions) => void) | null } + +export interface StrictProxyMiddlewareOptions { + /** + * A list of extra inspectable properties to add to the middleware. + * + * This is useful if you want to add support for framework-specific values. + */ + extraInspectables?: string[] +} diff --git a/tests/middleware.test.ts b/tests/middleware.test.ts index c0254db..857428c 100644 --- a/tests/middleware.test.ts +++ b/tests/middleware.test.ts @@ -1,5 +1,5 @@ import { cleanEnv, customCleanEnv, str } from '../src' -import { accessorMiddleware } from '../src/middleware' +import { accessorMiddleware, strictProxyMiddleware } from '../src/middleware' describe('customCleanEnv middleware type inference', () => { test('allows access to properties on the output object', () => { @@ -158,3 +158,14 @@ describe('proxy middleware', () => { expect(JSON.stringify(env)).toEqual('{"FOO":"foo"}') }) }) + +describe('strictProxyMiddleware', () => { + test('proxy allows extra inspectables applied through options', () => { + const env = customCleanEnv({ FOO: 'bar' }, { FOO: str() }, (cleaned, raw) => + strictProxyMiddleware(cleaned, raw, { extraInspectables: ['hello'] }), + ) + + // @ts-expect-error This invalid usage should trigger a type error + expect(() => env.hello).not.toThrow() + }) +})