/
utils.ts
59 lines (50 loc) · 1.75 KB
/
utils.ts
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
58
59
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import leven from 'leven';
import prettyFormat from 'pretty-format';
const BULLET: string = chalk.bold('\u25cf');
export const DEPRECATION = `${BULLET} Deprecation Warning`;
export const ERROR = `${BULLET} Validation Error`;
export const WARNING = `${BULLET} Validation Warning`;
export const format = (value: unknown): string =>
typeof value === 'function'
? value.toString()
: prettyFormat(value, {min: true});
export const formatPrettyObject = (value: unknown): string =>
typeof value === 'function'
? value.toString()
: JSON.stringify(value, null, 2).split('\n').join('\n ');
export class ValidationError extends Error {
name: string;
message: string;
constructor(name: string, message: string, comment?: string | null) {
super();
comment = comment ? '\n\n' + comment : '\n';
this.name = '';
this.message = chalk.red(chalk.bold(name) + ':\n\n' + message + comment);
Error.captureStackTrace(this, () => {});
}
}
export const logValidationWarning = (
name: string,
message: string,
comment?: string | null,
): void => {
comment = comment ? '\n\n' + comment : '\n';
console.warn(chalk.yellow(chalk.bold(name) + ':\n\n' + message + comment));
};
export const createDidYouMeanMessage = (
unrecognized: string,
allowedOptions: Array<string>,
): string => {
const suggestion = allowedOptions.find(option => {
const steps: number = leven(option, unrecognized);
return steps < 3;
});
return suggestion ? `Did you mean ${chalk.bold(format(suggestion))}?` : '';
};