UNPKG

estree-toolkit

Version:

Traverser, scope tracker, and more tools for working with ESTree AST

34 lines (33 loc) 1.37 kB
import { definitions, getFieldsOf } from './definitions.mjs'; import { runValidation } from './assert.mjs'; import { toCamelCase } from './helpers.mjs'; let shouldValidateNodes = true; export const setNodeValidationEnabled = (state) => { shouldValidateNodes = state; }; export const getNodeValidationEnabled = () => shouldValidateNodes; export const builders = {}; for (const key in definitions) { const nodeType = key; const definition = definitions[nodeType]; const { fields } = definition; const fieldNames = getFieldsOf(definition, 'builder'); builders[toCamelCase(nodeType)] = (...args) => { const node = { type: nodeType }; fieldNames.forEach((fieldName, index) => { const field = fields[fieldName]; node[fieldName] = args[index] !== undefined ? args[index] : ('default' in field ? (typeof field.default == 'function' ? field.default(node) : field.default) : /* istanbul ignore next */ args[index]); if (shouldValidateNodes && field.validate != null) { runValidation(field.validate, node[fieldName]); } }); if (shouldValidateNodes && definition.finalValidate != null) { runValidation(definition.finalValidate, node); } return node; }; }