Debian Codegraph @

packages/babel-helper-validator-option/src/validator.ts

raw symbols SCIP
1 import { findSuggestion } from "./find-suggestion";
2
3 export class OptionValidator {
4 declare descriptor: string;
5 constructor(descriptor: string) {
6 this.descriptor = descriptor;
7 }
8
9 /**
10 * Validate if the given `options` follow the name of keys defined in the `TopLevelOptionShape`
11 *
12 * @param {Object} options
13 * @param {Object} TopLevelOptionShape
14 * An object with all the valid key names that `options` should be allowed to have
15 * The property values of `TopLevelOptionShape` can be arbitrary
16 * @memberof OptionValidator
17 */
18 validateTopLevelOptions(options: Object, TopLevelOptionShape: Object): void {
19 const validOptionNames = Object.keys(TopLevelOptionShape);
20 for (const option of Object.keys(options)) {
21 if (!validOptionNames.includes(option)) {
22 throw new Error(
23 this.formatMessage(`'${option}' is not a valid top-level option.
24 - Did you mean '${findSuggestion(option, validOptionNames)}'?`),
25 );
26 }
27 }
28 }
29
30 // note: we do not consider rewrite them to high order functions
31 // until we have to support `validateNumberOption`.
32 validateBooleanOption<T>(
33 name: string,
34 value?: boolean,
35 defaultValue?: T,
36 ): boolean | T {
37 if (value === undefined) {
38 return defaultValue;
39 } else {
40 this.invariant(
41 typeof value === "boolean",
42 `'${name}' option must be a boolean.`,
43 );
44 }
45 return value;
46 }
47
48 validateStringOption<T>(
49 name: string,
50 value?: string,
51 defaultValue?: T,
52 ): string | T {
53 if (value === undefined) {
54 return defaultValue;
55 } else {
56 this.invariant(
57 typeof value === "string",
58 `'${name}' option must be a string.`,
59 );
60 }
61 return value;
62 }
63 /**
64 * A helper interface copied from the `invariant` npm package.
65 * It throws given `message` when `condition` is not met
66 *
67 * @param {boolean} condition
68 * @param {string} message
69 * @memberof OptionValidator
70 */
71 invariant(condition: boolean, message: string): void {
72 if (!condition) {
73 throw new Error(this.formatMessage(message));
74 }
75 }
76
77 formatMessage(message: string): string {
78 return `${this.descriptor}: ${message}`;
79 }
80 }