1'use strict'; 2 3// This file is a proxy of the original file located at: 4// https://github.com/nodejs/node/blob/main/lib/internal/validators.js 5// Every addition or modification to this file must be evaluated 6// during the PR review. 7 8const { 9 ArrayIsArray, 10 ArrayPrototypeIncludes, 11 ArrayPrototypeJoin, 12} = require('./primordials'); 13 14const { 15 codes: { 16 ERR_INVALID_ARG_TYPE 17 } 18} = require('./errors'); 19 20function validateString(value, name) { 21 if (typeof value !== 'string') { 22 throw new ERR_INVALID_ARG_TYPE(name, 'String', value); 23 } 24} 25 26function validateUnion(value, name, union) { 27 if (!ArrayPrototypeIncludes(union, value)) { 28 throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value); 29 } 30} 31 32function validateBoolean(value, name) { 33 if (typeof value !== 'boolean') { 34 throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value); 35 } 36} 37 38function validateArray(value, name) { 39 if (!ArrayIsArray(value)) { 40 throw new ERR_INVALID_ARG_TYPE(name, 'Array', value); 41 } 42} 43 44function validateStringArray(value, name) { 45 validateArray(value, name); 46 for (let i = 0; i < value.length; i++) { 47 validateString(value[i], `${name}[${i}]`); 48 } 49} 50 51function validateBooleanArray(value, name) { 52 validateArray(value, name); 53 for (let i = 0; i < value.length; i++) { 54 validateBoolean(value[i], `${name}[${i}]`); 55 } 56} 57 58/** 59 * @param {unknown} value 60 * @param {string} name 61 * @param {{ 62 * allowArray?: boolean, 63 * allowFunction?: boolean, 64 * nullable?: boolean 65 * }} [options] 66 */ 67function validateObject(value, name, options) { 68 const useDefaultOptions = options == null; 69 const allowArray = useDefaultOptions ? false : options.allowArray; 70 const allowFunction = useDefaultOptions ? false : options.allowFunction; 71 const nullable = useDefaultOptions ? false : options.nullable; 72 if ((!nullable && value === null) || 73 (!allowArray && ArrayIsArray(value)) || 74 (typeof value !== 'object' && ( 75 !allowFunction || typeof value !== 'function' 76 ))) { 77 throw new ERR_INVALID_ARG_TYPE(name, 'Object', value); 78 } 79} 80 81module.exports = { 82 validateArray, 83 validateObject, 84 validateString, 85 validateStringArray, 86 validateUnion, 87 validateBoolean, 88 validateBooleanArray, 89}; 90