Debian Codegraph @

packages/babel-types/scripts/generators/asserts.js

raw
1 import {
2 DEPRECATED_KEYS,
3 FLIPPED_ALIAS_KEYS,
4 NODE_FIELDS,
5 VISITOR_KEYS,
6 } from "../../lib/index.js";
7
8 function addAssertHelper(type) {
9 const result =
10 NODE_FIELDS[type] || FLIPPED_ALIAS_KEYS[type]
11 ? `node is t.${type}`
12 : "boolean";
13
14 return `export function assert${type}(node: object | null | undefined, opts?: object | null): asserts ${
15 result === "boolean" ? "node" : result
16 } {
17 assert("${type}", node, opts) }
18 `;
19 }
20
21 export default function generateAsserts() {
22 let output = `/*
23 * This file is auto-generated! Do not modify it directly.
24 * To re-generate run 'make build'
25 */
26 import is from "../../validators/is";
27 import type * as t from "../..";
28
29 function assert(type: string, node: any, opts?: any): void {
30 if (!is(type, node, opts)) {
31 throw new Error(
32 \`Expected type "\${type}" with option \${JSON.stringify(opts)}, \` +
33 \`but instead got "\${node.type}".\`,
34 );
35 }
36 }\n\n`;
37
38 Object.keys(VISITOR_KEYS).forEach(type => {
39 output += addAssertHelper(type);
40 });
41
42 Object.keys(FLIPPED_ALIAS_KEYS).forEach(type => {
43 output += addAssertHelper(type);
44 });
45
46 Object.keys(DEPRECATED_KEYS).forEach(type => {
47 const newType = DEPRECATED_KEYS[type];
48 output += `export function assert${type}(node: any, opts: any): void {
49 console.trace("The node type ${type} has been renamed to ${newType}");
50 assert("${type}", node, opts);
51 }\n`;
52 });
53
54 return output;
55 }