Skip to content

Commit

Permalink
Ensure that an array validator is followed by assertEach
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Feb 12, 2021
1 parent b8d0958 commit 4a20844
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
6 changes: 3 additions & 3 deletions packages/babel-types/src/ast-types/generated/index.ts
Expand Up @@ -820,7 +820,7 @@ export interface ClassDeclaration extends BaseNode {
export interface ExportAllDeclaration extends BaseNode {
type: "ExportAllDeclaration";
source: StringLiteral;
assertions?: ImportAttribute | null;
assertions?: Array<ImportAttribute> | null;
exportKind?: "type" | "value" | null;
}

Expand All @@ -840,7 +840,7 @@ export interface ExportNamedDeclaration extends BaseNode {
ExportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier
>;
source?: StringLiteral | null;
assertions?: ImportAttribute | null;
assertions?: Array<ImportAttribute> | null;
exportKind?: "type" | "value" | null;
}

Expand All @@ -864,7 +864,7 @@ export interface ImportDeclaration extends BaseNode {
ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier
>;
source: StringLiteral;
assertions?: ImportAttribute | null;
assertions?: Array<ImportAttribute> | null;
importKind?: "type" | "typeof" | "value" | null;
}

Expand Down
34 changes: 26 additions & 8 deletions packages/babel-types/src/definitions/utils.ts
Expand Up @@ -19,12 +19,18 @@ function getType(val) {
}
}

// TODO: Import and use Node instead of any
type Validator = { chainOf?: Validator[] } & ((
parent: any,
key: string,
node: any,
) => void);
type Validator = (
| { type: string }
| { each: Validator }
| { chainOf: Validator[] }
| { oneOf: any[] }
| { oneOfNodeTypes: string[] }
| { oneOfNodeOrValueTypes: string[] }
| { shapeOf: { [x: string]: FieldOptions } }
| {}
) &
// TODO: Import and use Node instead of any
((parent: any, key: string, node: any) => void);

type FieldOptions = {
default?: any;
Expand Down Expand Up @@ -218,12 +224,24 @@ export function assertOptionalChainStart(): Validator {
}

export function chain(...fns: Array<Validator>): Validator {
const validate: Validator = function (...args) {
function validate(...args: Parameters<Validator>) {
for (const fn of fns) {
fn(...args);
}
};
}
validate.chainOf = fns;

if (
fns.length >= 2 &&
"type" in fns[0] &&
fns[0].type === "array" &&
!("each" in fns[1])
) {
throw new Error(
`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`,
);
}

return validate;
}

Expand Down

0 comments on commit 4a20844

Please sign in to comment.