| 1 |
import is from "../validators/is"; |
| 2 |
import { validateField, validateChild } from "../validators/validate"; |
| 3 |
import type * as t from ".."; |
| 4 |
|
| 5 |
export const VISITOR_KEYS: Record<string, string[]> = {}; |
| 6 |
export const ALIAS_KEYS: Partial<Record<NodeTypesWithoutComment, string[]>> = |
| 7 |
{}; |
| 8 |
export const FLIPPED_ALIAS_KEYS: Record<string, NodeTypesWithoutComment[]> = {}; |
| 9 |
export const NODE_FIELDS: Record<string, FieldDefinitions> = {}; |
| 10 |
export const BUILDER_KEYS: Record<string, string[]> = {}; |
| 11 |
export const DEPRECATED_KEYS: Record<string, NodeTypesWithoutComment> = {}; |
| 12 |
export const NODE_PARENT_VALIDATIONS: Record<string, Validator> = {}; |
| 13 |
|
| 14 |
function getType(val: any) { |
| 15 |
if (Array.isArray(val)) { |
| 16 |
return "array"; |
| 17 |
} else if (val === null) { |
| 18 |
return "null"; |
| 19 |
} else { |
| 20 |
return typeof val; |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
type NodeTypesWithoutComment = t.Node["type"] | keyof t.Aliases; |
| 25 |
|
| 26 |
type NodeTypes = NodeTypesWithoutComment | t.Comment["type"]; |
| 27 |
|
| 28 |
type PrimitiveTypes = ReturnType<typeof getType>; |
| 29 |
|
| 30 |
type FieldDefinitions = { |
| 31 |
[x: string]: FieldOptions; |
| 32 |
}; |
| 33 |
|
| 34 |
type DefineTypeOpts = { |
| 35 |
fields?: FieldDefinitions; |
| 36 |
visitor?: Array<string>; |
| 37 |
aliases?: Array<string>; |
| 38 |
builder?: Array<string>; |
| 39 |
inherits?: NodeTypes; |
| 40 |
deprecatedAlias?: string; |
| 41 |
validate?: Validator; |
| 42 |
}; |
| 43 |
|
| 44 |
export type Validator = ( |
| 45 |
| { type: PrimitiveTypes } |
| 46 |
| { each: Validator } |
| 47 |
| { chainOf: Validator[] } |
| 48 |
| { oneOf: any[] } |
| 49 |
| { oneOfNodeTypes: NodeTypes[] } |
| 50 |
| { oneOfNodeOrValueTypes: (NodeTypes | PrimitiveTypes)[] } |
| 51 |
| { shapeOf: { [x: string]: FieldOptions } } |
| 52 |
| {} |
| 53 |
) & |
| 54 |
((node: t.Node, key: string, val: any) => void); |
| 55 |
|
| 56 |
export type FieldOptions = { |
| 57 |
default?: string | number | boolean | []; |
| 58 |
optional?: boolean; |
| 59 |
validate?: Validator; |
| 60 |
}; |
| 61 |
|
| 62 |
export function validate(validate: Validator): FieldOptions { |
| 63 |
return { validate }; |
| 64 |
} |
| 65 |
|
| 66 |
export function typeIs(typeName: NodeTypes | NodeTypes[]) { |
| 67 |
return typeof typeName === "string" |
| 68 |
? assertNodeType(typeName) |
| 69 |
: assertNodeType(...typeName); |
| 70 |
} |
| 71 |
|
| 72 |
export function validateType(typeName: NodeTypes | NodeTypes[]) { |
| 73 |
return validate(typeIs(typeName)); |
| 74 |
} |
| 75 |
|
| 76 |
export function validateOptional(validate: Validator): FieldOptions { |
| 77 |
return { validate, optional: true }; |
| 78 |
} |
| 79 |
|
| 80 |
export function validateOptionalType( |
| 81 |
typeName: NodeTypes | NodeTypes[], |
| 82 |
): FieldOptions { |
| 83 |
return { validate: typeIs(typeName), optional: true }; |
| 84 |
} |
| 85 |
|
| 86 |
export function arrayOf(elementType: Validator): Validator { |
| 87 |
return chain(assertValueType("array"), assertEach(elementType)); |
| 88 |
} |
| 89 |
|
| 90 |
export function arrayOfType(typeName: NodeTypes | NodeTypes[]) { |
| 91 |
return arrayOf(typeIs(typeName)); |
| 92 |
} |
| 93 |
|
| 94 |
export function validateArrayOfType(typeName: NodeTypes | NodeTypes[]) { |
| 95 |
return validate(arrayOfType(typeName)); |
| 96 |
} |
| 97 |
|
| 98 |
export function assertEach(callback: Validator): Validator { |
| 99 |
function validator(node: t.Node, key: string, val: any) { |
| 100 |
if (!Array.isArray(val)) return; |
| 101 |
|
| 102 |
for (let i = 0; i < val.length; i++) { |
| 103 |
const subkey = `${key}[${i}]`; |
| 104 |
const v = val[i]; |
| 105 |
callback(node, subkey, v); |
| 106 |
if (process.env.BABEL_TYPES_8_BREAKING) validateChild(node, subkey, v); |
| 107 |
} |
| 108 |
} |
| 109 |
validator.each = callback; |
| 110 |
return validator; |
| 111 |
} |
| 112 |
|
| 113 |
export function assertOneOf(...values: Array<any>): Validator { |
| 114 |
function validate(node: any, key: string, val: any) { |
| 115 |
if (values.indexOf(val) < 0) { |
| 116 |
throw new TypeError( |
| 117 |
`Property ${key} expected value to be one of ${JSON.stringify( |
| 118 |
values, |
| 119 |
)} but got ${JSON.stringify(val)}`, |
| 120 |
); |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
validate.oneOf = values; |
| 125 |
|
| 126 |
return validate; |
| 127 |
} |
| 128 |
|
| 129 |
export function assertNodeType(...types: NodeTypes[]): Validator { |
| 130 |
function validate(node: t.Node, key: string, val: any) { |
| 131 |
for (const type of types) { |
| 132 |
if (is(type, val)) { |
| 133 |
validateChild(node, key, val); |
| 134 |
return; |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
throw new TypeError( |
| 139 |
`Property ${key} of ${ |
| 140 |
node.type |
| 141 |
} expected node to be of a type ${JSON.stringify( |
| 142 |
types, |
| 143 |
)} but instead got ${JSON.stringify(val?.type)}`, |
| 144 |
); |
| 145 |
} |
| 146 |
|
| 147 |
validate.oneOfNodeTypes = types; |
| 148 |
|
| 149 |
return validate; |
| 150 |
} |
| 151 |
|
| 152 |
export function assertNodeOrValueType( |
| 153 |
...types: (NodeTypes | PrimitiveTypes)[] |
| 154 |
): Validator { |
| 155 |
function validate(node: t.Node, key: string, val: any) { |
| 156 |
for (const type of types) { |
| 157 |
if (getType(val) === type || is(type, val)) { |
| 158 |
validateChild(node, key, val); |
| 159 |
return; |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
throw new TypeError( |
| 164 |
`Property ${key} of ${ |
| 165 |
node.type |
| 166 |
} expected node to be of a type ${JSON.stringify( |
| 167 |
types, |
| 168 |
)} but instead got ${JSON.stringify(val?.type)}`, |
| 169 |
); |
| 170 |
} |
| 171 |
|
| 172 |
validate.oneOfNodeOrValueTypes = types; |
| 173 |
|
| 174 |
return validate; |
| 175 |
} |
| 176 |
|
| 177 |
export function assertValueType(type: PrimitiveTypes): Validator { |
| 178 |
function validate(node: t.Node, key: string, val: any) { |
| 179 |
const valid = getType(val) === type; |
| 180 |
|
| 181 |
if (!valid) { |
| 182 |
throw new TypeError( |
| 183 |
`Property ${key} expected type of ${type} but got ${getType(val)}`, |
| 184 |
); |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
validate.type = type; |
| 189 |
|
| 190 |
return validate; |
| 191 |
} |
| 192 |
|
| 193 |
export function assertShape(shape: { [x: string]: FieldOptions }): Validator { |
| 194 |
function validate(node: t.Node, key: string, val: any) { |
| 195 |
const errors = []; |
| 196 |
for (const property of Object.keys(shape)) { |
| 197 |
try { |
| 198 |
validateField(node, property, val[property], shape[property]); |
| 199 |
} catch (error) { |
| 200 |
if (error instanceof TypeError) { |
| 201 |
errors.push(error.message); |
| 202 |
continue; |
| 203 |
} |
| 204 |
throw error; |
| 205 |
} |
| 206 |
} |
| 207 |
if (errors.length) { |
| 208 |
throw new TypeError( |
| 209 |
`Property ${key} of ${ |
| 210 |
node.type |
| 211 |
} expected to have the following:\n${errors.join("\n")}`, |
| 212 |
); |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
validate.shapeOf = shape; |
| 217 |
|
| 218 |
return validate; |
| 219 |
} |
| 220 |
|
| 221 |
export function assertOptionalChainStart(): Validator { |
| 222 |
function validate(node: t.Node) { |
| 223 |
let current = node; |
| 224 |
while (node) { |
| 225 |
const { type } = current; |
| 226 |
if (type === "OptionalCallExpression") { |
| 227 |
if (current.optional) return; |
| 228 |
current = current.callee; |
| 229 |
continue; |
| 230 |
} |
| 231 |
|
| 232 |
if (type === "OptionalMemberExpression") { |
| 233 |
if (current.optional) return; |
| 234 |
current = current.object; |
| 235 |
continue; |
| 236 |
} |
| 237 |
|
| 238 |
break; |
| 239 |
} |
| 240 |
|
| 241 |
throw new TypeError( |
| 242 |
`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${current?.type}`, |
| 243 |
); |
| 244 |
} |
| 245 |
|
| 246 |
return validate; |
| 247 |
} |
| 248 |
|
| 249 |
export function chain(...fns: Array<Validator>): Validator { |
| 250 |
function validate(...args: Parameters<Validator>) { |
| 251 |
for (const fn of fns) { |
| 252 |
fn(...args); |
| 253 |
} |
| 254 |
} |
| 255 |
validate.chainOf = fns; |
| 256 |
|
| 257 |
if ( |
| 258 |
fns.length >= 2 && |
| 259 |
"type" in fns[0] && |
| 260 |
fns[0].type === "array" && |
| 261 |
!("each" in fns[1]) |
| 262 |
) { |
| 263 |
throw new Error( |
| 264 |
`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`, |
| 265 |
); |
| 266 |
} |
| 267 |
|
| 268 |
return validate; |
| 269 |
} |
| 270 |
|
| 271 |
const validTypeOpts = [ |
| 272 |
"aliases", |
| 273 |
"builder", |
| 274 |
"deprecatedAlias", |
| 275 |
"fields", |
| 276 |
"inherits", |
| 277 |
"visitor", |
| 278 |
"validate", |
| 279 |
]; |
| 280 |
const validFieldKeys = ["default", "optional", "validate"]; |
| 281 |
|
| 282 |
const store = {} as Record<string, DefineTypeOpts>; |
| 283 |
|
| 284 |
// Wraps defineType to ensure these aliases are included. |
| 285 |
export function defineAliasedType(...aliases: string[]) { |
| 286 |
return (type: string, opts: DefineTypeOpts = {}) => { |
| 287 |
let defined = opts.aliases; |
| 288 |
if (!defined) { |
| 289 |
if (opts.inherits) defined = store[opts.inherits].aliases?.slice(); |
| 290 |
defined ??= []; |
| 291 |
opts.aliases = defined; |
| 292 |
} |
| 293 |
const additional = aliases.filter(a => !defined.includes(a)); |
| 294 |
defined.unshift(...additional); |
| 295 |
return defineType(type, opts); |
| 296 |
}; |
| 297 |
} |
| 298 |
|
| 299 |
export default function defineType(type: string, opts: DefineTypeOpts = {}) { |
| 300 |
const inherits = (opts.inherits && store[opts.inherits]) || {}; |
| 301 |
|
| 302 |
let fields = opts.fields; |
| 303 |
if (!fields) { |
| 304 |
fields = {}; |
| 305 |
if (inherits.fields) { |
| 306 |
const keys = Object.getOwnPropertyNames(inherits.fields); |
| 307 |
for (const key of keys) { |
| 308 |
const field = inherits.fields[key]; |
| 309 |
const def = field.default; |
| 310 |
if ( |
| 311 |
Array.isArray(def) ? def.length > 0 : def && typeof def === "object" |
| 312 |
) { |
| 313 |
throw new Error( |
| 314 |
"field defaults can only be primitives or empty arrays currently", |
| 315 |
); |
| 316 |
} |
| 317 |
fields[key] = { |
| 318 |
default: Array.isArray(def) ? [] : def, |
| 319 |
optional: field.optional, |
| 320 |
validate: field.validate, |
| 321 |
}; |
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
const visitor: Array<string> = opts.visitor || inherits.visitor || []; |
| 327 |
const aliases: Array<string> = opts.aliases || inherits.aliases || []; |
| 328 |
const builder: Array<string> = |
| 329 |
opts.builder || inherits.builder || opts.visitor || []; |
| 330 |
|
| 331 |
for (const k of Object.keys(opts)) { |
| 332 |
if (validTypeOpts.indexOf(k) === -1) { |
| 333 |
throw new Error(`Unknown type option "${k}" on ${type}`); |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
if (opts.deprecatedAlias) { |
| 338 |
DEPRECATED_KEYS[opts.deprecatedAlias] = type as NodeTypesWithoutComment; |
| 339 |
} |
| 340 |
|
| 341 |
// ensure all field keys are represented in `fields` |
| 342 |
for (const key of visitor.concat(builder)) { |
| 343 |
fields[key] = fields[key] || {}; |
| 344 |
} |
| 345 |
|
| 346 |
for (const key of Object.keys(fields)) { |
| 347 |
const field = fields[key]; |
| 348 |
|
| 349 |
if (field.default !== undefined && builder.indexOf(key) === -1) { |
| 350 |
field.optional = true; |
| 351 |
} |
| 352 |
if (field.default === undefined) { |
| 353 |
field.default = null; |
| 354 |
} else if (!field.validate && field.default != null) { |
| 355 |
field.validate = assertValueType(getType(field.default)); |
| 356 |
} |
| 357 |
|
| 358 |
for (const k of Object.keys(field)) { |
| 359 |
if (validFieldKeys.indexOf(k) === -1) { |
| 360 |
throw new Error(`Unknown field key "${k}" on ${type}.${key}`); |
| 361 |
} |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
VISITOR_KEYS[type] = opts.visitor = visitor; |
| 366 |
BUILDER_KEYS[type] = opts.builder = builder; |
| 367 |
NODE_FIELDS[type] = opts.fields = fields; |
| 368 |
ALIAS_KEYS[type as NodeTypesWithoutComment] = opts.aliases = aliases; |
| 369 |
aliases.forEach(alias => { |
| 370 |
FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; |
| 371 |
FLIPPED_ALIAS_KEYS[alias].push(type as NodeTypesWithoutComment); |
| 372 |
}); |
| 373 |
|
| 374 |
if (opts.validate) { |
| 375 |
NODE_PARENT_VALIDATIONS[type] = opts.validate; |
| 376 |
} |
| 377 |
|
| 378 |
store[type] = opts; |
| 379 |
} |