| 1 |
export default function stringifyValidator(validator, nodePrefix) { |
| 2 |
if (validator === undefined) { |
| 3 |
return "any"; |
| 4 |
} |
| 5 |
|
| 6 |
if (validator.each) { |
| 7 |
return `Array<${stringifyValidator(validator.each, nodePrefix)}>`; |
| 8 |
} |
| 9 |
|
| 10 |
if (validator.chainOf) { |
| 11 |
const ret = stringifyValidator(validator.chainOf[1], nodePrefix); |
| 12 |
return Array.isArray(ret) && ret.length === 1 && ret[0] === "any" |
| 13 |
? stringifyValidator(validator.chainOf[0], nodePrefix) |
| 14 |
: ret; |
| 15 |
} |
| 16 |
|
| 17 |
if (validator.oneOf) { |
| 18 |
return validator.oneOf.map(JSON.stringify).join(" | "); |
| 19 |
} |
| 20 |
|
| 21 |
if (validator.oneOfNodeTypes) { |
| 22 |
return validator.oneOfNodeTypes.map(_ => nodePrefix + _).join(" | "); |
| 23 |
} |
| 24 |
|
| 25 |
if (validator.oneOfNodeOrValueTypes) { |
| 26 |
return validator.oneOfNodeOrValueTypes |
| 27 |
.map(_ => { |
| 28 |
return isValueType(_) ? _ : nodePrefix + _; |
| 29 |
}) |
| 30 |
.join(" | "); |
| 31 |
} |
| 32 |
|
| 33 |
if (validator.type) { |
| 34 |
return validator.type; |
| 35 |
} |
| 36 |
|
| 37 |
if (validator.shapeOf) { |
| 38 |
return ( |
| 39 |
"{ " + |
| 40 |
Object.keys(validator.shapeOf) |
| 41 |
.map(shapeKey => { |
| 42 |
const propertyDefinition = validator.shapeOf[shapeKey]; |
| 43 |
if (propertyDefinition.validate) { |
| 44 |
const isOptional = |
| 45 |
propertyDefinition.optional || propertyDefinition.default != null; |
| 46 |
return ( |
| 47 |
shapeKey + |
| 48 |
(isOptional ? "?: " : ": ") + |
| 49 |
stringifyValidator(propertyDefinition.validate) |
| 50 |
); |
| 51 |
} |
| 52 |
return null; |
| 53 |
}) |
| 54 |
.filter(Boolean) |
| 55 |
.join(", ") + |
| 56 |
" }" |
| 57 |
); |
| 58 |
} |
| 59 |
|
| 60 |
return ["any"]; |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Heuristic to decide whether or not the given type is a value type (eg. "null") |
| 65 |
* or a Node type (eg. "Expression"). |
| 66 |
*/ |
| 67 |
export function isValueType(type) { |
| 68 |
return type.charAt(0).toLowerCase() === type.charAt(0); |
| 69 |
} |