diff --git a/src/index.test.ts b/src/index.test.ts index 6775c1c..9b53565 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -537,6 +537,98 @@ testLog( ['remove'], ); +testLog( + 'should use input censor when redacting', + { + redact: 'Should be redacted', + }, + { + redact: '[SHHH]', + }, + 'info', + { + redact: { + paths: ['redact'], + censor: (_value, _path) => '[SHHH]', + }, + }, +); + +testLog( + 'should not use input censor when removing', + { + remove: 'Should be "removed"', + }, + {}, + 'info', + { + redact: { + paths: ['remove'], + remove: true, + censor: (_value, _path) => 'You have been erased!', + }, + }, + ['remove'], +); + +testLog( + 'should not use input censor when redacting and removing with no redact paths', + { + remove: 'Should be "removed"', + }, + {}, + 'info', + { + redact: { + paths: [], + removePaths: ['remove'], + censor: (_value, _path) => 'You have been erased!', + }, + }, + ['remove'], +); + +testLog( + 'should use input censor function to redact when redacting and removing', + { + redact: 'Should be redacted', + remove: 'Should be "removed"', + }, + { + redact: '[SHHH]', + }, + 'info', + { + redact: { + paths: ['redact'], + removePaths: ['remove'], + censor: (_value, path) => + path.includes('redact') ? '[SHHH]' : 'You have been erased!', + }, + }, + ['remove'], +); + +testLog( + 'should use input censor text to redact when redacting and removing', + { + redact: 'Should be redacted', + remove: 'Should be "removed"', + }, + { + redact: '[SHHH]', + }, + 'info', + { + redact: { + paths: ['redact'], + removePaths: ['remove'], + censor: '[SHHH]', + }, + }, + ['remove'], +); + testLog( 'should remove specified paths', { diff --git a/src/redact/index.ts b/src/redact/index.ts index 344c022..44acf44 100644 --- a/src/redact/index.ts +++ b/src/redact/index.ts @@ -69,15 +69,20 @@ const configureRedactCensor = (redact: ExtendedRedact): ExtendedRedact => { return redact; } - const { paths: redactPaths, removePaths } = redact; - const redactSet = new Set(redactPaths); + const { paths: redactPaths, removePaths, censor } = redact; + const removeSet = new Set(removePaths); + const censorText = typeof censor === 'string' ? censor : '[Redacted]'; + const censorPath = (value: unknown, path: string[]): unknown => + typeof censor === 'function' ? censor(value, path) : censorText; return redactPaths.length === 0 - ? { paths: removePaths, remove: true } + ? { paths: removePaths, remove: true, censor } : { paths: [...redactPaths, ...removePaths], - censor: (_value, path) => - redactSet.has(keyFromPath(path)) ? '[Redacted]' : undefined, + censor: (value, path) => + removeSet.has(keyFromPath(path)) + ? undefined + : censorPath(value, path), }; };