Skip to content

Commit

Permalink
sanitize ansi codes in error message and stack
Browse files Browse the repository at this point in the history
  • Loading branch information
yannbf committed Aug 31, 2023
1 parent 7b268e1 commit 15b8f83
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
16 changes: 16 additions & 0 deletions code/lib/telemetry/src/sanitize.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
/* eslint-disable local-rules/no-uncategorized-errors */
import { sanitizeError, cleanPaths } from './sanitize';

describe(`Errors Helpers`, () => {
describe(`sanitizeError`, () => {
it(`Sanitizes ansi codes in error`, () => {
const errorMessage = `\u001B[4mStorybook\u001B[0m`;
let e: any;
try {
throw new Error(errorMessage);
} catch (error) {
e = error;
}

const sanitizedError = sanitizeError(e);

expect(sanitizedError.message).toEqual('Storybook');
expect(sanitizedError.stack).toContain('Error: Storybook');
});

it(`Sanitizes current path from error stacktraces`, () => {
const errorMessage = `this is a test`;
let e: any;
Expand Down
15 changes: 14 additions & 1 deletion code/lib/telemetry/src/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ function regexpEscape(str: string): string {
return str.replace(/[-[/{}()*+?.\\^$|]/g, `\\$&`);
}

export function removeAnsiEscapeCodes(input: string): string {
// eslint-disable-next-line no-control-regex
return input.replace(/\u001B\[[0-9;]*m/g, '');
}

export function cleanPaths(str: string, separator: string = sep): string {
if (!str) return str;

Expand All @@ -35,7 +40,15 @@ export function cleanPaths(str: string, separator: string = sep): string {
export function sanitizeError(error: Error, pathSeparator: string = sep) {
try {
// Hack because Node
error = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)));
error = JSON.parse(
JSON.stringify(error, [...Object.getOwnPropertyNames(error), 'message', 'name'])
);
if (error.message) {
error.message = removeAnsiEscapeCodes(error.message);
}
if (error.stack) {
error.stack = removeAnsiEscapeCodes(error.stack);
}

// Removes all user paths
const errorString = cleanPaths(JSON.stringify(error), pathSeparator);
Expand Down

0 comments on commit 15b8f83

Please sign in to comment.