Debian Codegraph @

packages/babel-types/src/validators/validate.ts

raw
1 import {
2 NODE_FIELDS,
3 NODE_PARENT_VALIDATIONS,
4 type FieldOptions,
5 } from "../definitions";
6 import type * as t from "..";
7
8 export default function validate(
9 node: t.Node | undefined | null,
10 key: string,
11 val: any,
12 ): void {
13 if (!node) return;
14
15 const fields = NODE_FIELDS[node.type];
16 if (!fields) return;
17
18 const field = fields[key];
19 validateField(node, key, val, field);
20 validateChild(node, key, val);
21 }
22
23 export function validateField(
24 node: t.Node | undefined | null,
25 key: string,
26 val: any,
27 field: FieldOptions | undefined | null,
28 ): void {
29 if (!field?.validate) return;
30 if (field.optional && val == null) return;
31
32 field.validate(node, key, val);
33 }
34
35 export function validateChild(
36 node: t.Node | undefined | null,
37 key: string,
38 val?: t.Node | undefined | null,
39 ) {
40 if (val == null) return;
41 const validate = NODE_PARENT_VALIDATIONS[val.type];
42 if (!validate) return;
43 validate(node, key, val);
44 }