lib: extract validateString validator

Pulls out a common argument validator to `internal/validators`

PR-URL: https://github.com/nodejs/node/pull/22101
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Anatoli Papirovski <apapirovski@mac.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Jon Moss 2018-08-02 18:51:02 -04:00
parent 080316b32a
commit e570ae79f5
17 changed files with 52 additions and 85 deletions

View File

@ -45,6 +45,7 @@ const {
ERR_STREAM_CANNOT_PIPE, ERR_STREAM_CANNOT_PIPE,
ERR_STREAM_WRITE_AFTER_END ERR_STREAM_WRITE_AFTER_END
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { CRLF, debug } = common; const { CRLF, debug } = common;
@ -480,9 +481,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
OutgoingMessage.prototype.getHeader = function getHeader(name) { OutgoingMessage.prototype.getHeader = function getHeader(name) {
if (typeof name !== 'string') { validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
}
const headers = this[outHeadersKey]; const headers = this[outHeadersKey];
if (headers === null) if (headers === null)
@ -516,19 +515,14 @@ OutgoingMessage.prototype.getHeaders = function getHeaders() {
OutgoingMessage.prototype.hasHeader = function hasHeader(name) { OutgoingMessage.prototype.hasHeader = function hasHeader(name) {
if (typeof name !== 'string') { validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
}
return this[outHeadersKey] !== null && return this[outHeadersKey] !== null &&
!!this[outHeadersKey][name.toLowerCase()]; !!this[outHeadersKey][name.toLowerCase()];
}; };
OutgoingMessage.prototype.removeHeader = function removeHeader(name) { OutgoingMessage.prototype.removeHeader = function removeHeader(name) {
if (typeof name !== 'string') { validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
}
if (this._header) { if (this._header) {
throw new ERR_HTTP_HEADERS_SENT('remove'); throw new ERR_HTTP_HEADERS_SENT('remove');

View File

@ -51,6 +51,7 @@ const {
ERR_TLS_SESSION_ATTACK, ERR_TLS_SESSION_ATTACK,
ERR_TLS_SNI_FROM_SERVER ERR_TLS_SNI_FROM_SERVER
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const kConnectOptions = Symbol('connect-options'); const kConnectOptions = Symbol('connect-options');
const kDisableRenegotiation = Symbol('disable-renegotiation'); const kDisableRenegotiation = Symbol('disable-renegotiation');
const kErrorEmitted = Symbol('error-emitted'); const kErrorEmitted = Symbol('error-emitted');
@ -646,9 +647,7 @@ TLSSocket.prototype._start = function() {
}; };
TLSSocket.prototype.setServername = function(name) { TLSSocket.prototype.setServername = function(name) {
if (typeof name !== 'string') { validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
}
if (this._tlsOptions.isServer) { if (this._tlsOptions.isServer) {
throw new ERR_TLS_SNI_FROM_SERVER(); throw new ERR_TLS_SNI_FROM_SERVER();

View File

@ -2,9 +2,9 @@
const { const {
ERR_ASYNC_CALLBACK, ERR_ASYNC_CALLBACK,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ASYNC_ID ERR_INVALID_ASYNC_ID
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const internal_async_hooks = require('internal/async_hooks'); const internal_async_hooks = require('internal/async_hooks');
// Get functions // Get functions
@ -140,8 +140,7 @@ function showEmitBeforeAfterWarning() {
class AsyncResource { class AsyncResource {
constructor(type, opts = {}) { constructor(type, opts = {}) {
if (typeof type !== 'string') validateString(type, 'type');
throw new ERR_INVALID_ARG_TYPE('type', 'string', type);
if (typeof opts === 'number') { if (typeof opts === 'number') {
opts = { triggerAsyncId: opts, requireManualDestroy: false }; opts = { triggerAsyncId: opts, requireManualDestroy: false };

View File

@ -69,6 +69,7 @@ const {
ERR_NO_LONGER_SUPPORTED, ERR_NO_LONGER_SUPPORTED,
ERR_UNKNOWN_ENCODING ERR_UNKNOWN_ENCODING
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const internalBuffer = require('internal/buffer'); const internalBuffer = require('internal/buffer');
@ -841,9 +842,7 @@ function _fill(buf, val, start, end, encoding) {
const normalizedEncoding = normalizeEncoding(encoding); const normalizedEncoding = normalizeEncoding(encoding);
if (normalizedEncoding === undefined) { if (normalizedEncoding === undefined) {
if (typeof encoding !== 'string') { validateString(encoding, 'encoding');
throw new ERR_INVALID_ARG_TYPE('encoding', 'string', encoding);
}
throw new ERR_UNKNOWN_ENCODING(encoding); throw new ERR_UNKNOWN_ENCODING(encoding);
} }

View File

@ -37,6 +37,7 @@ const {
ERR_INVALID_OPT_VALUE, ERR_INVALID_OPT_VALUE,
ERR_OUT_OF_RANGE ERR_OUT_OF_RANGE
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const child_process = require('internal/child_process'); const child_process = require('internal/child_process');
const { const {
_validateStdio, _validateStdio,
@ -390,8 +391,7 @@ function _convertCustomFds(options) {
} }
function normalizeSpawnArguments(file, args, options) { function normalizeSpawnArguments(file, args, options) {
if (typeof file !== 'string') validateString(file, 'file');
throw new ERR_INVALID_ARG_TYPE('file', 'string', file);
if (file.length === 0) if (file.length === 0)
throw new ERR_INVALID_ARG_VALUE('file', file, 'cannot be empty'); throw new ERR_INVALID_ARG_VALUE('file', file, 'cannot be empty');

View File

@ -39,6 +39,7 @@ const {
ERR_SOCKET_DGRAM_NOT_RUNNING, ERR_SOCKET_DGRAM_NOT_RUNNING,
ERR_INVALID_FD_TYPE ERR_INVALID_FD_TYPE
} = errors.codes; } = errors.codes;
const { validateString } = require('internal/validators');
const { Buffer } = require('buffer'); const { Buffer } = require('buffer');
const util = require('util'); const util = require('util');
const { isUint8Array } = require('internal/util/types'); const { isUint8Array } = require('internal/util/types');
@ -322,9 +323,7 @@ Socket.prototype.sendto = function(buffer,
throw new ERR_INVALID_ARG_TYPE('port', 'number', port); throw new ERR_INVALID_ARG_TYPE('port', 'number', port);
} }
if (typeof address !== 'string') { validateString(address, 'address');
throw new ERR_INVALID_ARG_TYPE('address', 'string', address);
}
this.send(buffer, offset, length, port, address, callback); this.send(buffer, offset, length, port, address, callback);
}; };
@ -623,11 +622,7 @@ Socket.prototype.setMulticastLoopback = function(arg) {
Socket.prototype.setMulticastInterface = function(interfaceAddress) { Socket.prototype.setMulticastInterface = function(interfaceAddress) {
healthCheck(this); healthCheck(this);
validateString(interfaceAddress, 'interfaceAddress');
if (typeof interfaceAddress !== 'string') {
throw new ERR_INVALID_ARG_TYPE(
'interfaceAddress', 'string', interfaceAddress);
}
const err = this[kStateSymbol].handle.setMulticastInterface(interfaceAddress); const err = this[kStateSymbol].handle.setMulticastInterface(interfaceAddress);
if (err) { if (err) {

View File

@ -39,6 +39,7 @@ const {
ERR_MISSING_ARGS, ERR_MISSING_ARGS,
ERR_SOCKET_BAD_PORT ERR_SOCKET_BAD_PORT
} = errors.codes; } = errors.codes;
const { validateString } = require('internal/validators');
const { const {
GetAddrInfoReqWrap, GetAddrInfoReqWrap,
@ -206,9 +207,8 @@ function resolver(bindingName) {
callback = arguments[2]; callback = arguments[2];
} }
if (typeof name !== 'string') { validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name); if (typeof callback !== 'function') {
} else if (typeof callback !== 'function') {
throw new ERR_INVALID_CALLBACK(); throw new ERR_INVALID_CALLBACK();
} }

View File

@ -9,6 +9,7 @@ const {
ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_TYPE,
ERR_INVALID_CALLBACK ERR_INVALID_CALLBACK
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const util = require('util'); const util = require('util');
const { Connection, open, url } = process.binding('inspector'); const { Connection, open, url } = process.binding('inspector');
const { originalConsole } = require('internal/process/per_thread'); const { originalConsole } = require('internal/process/per_thread');
@ -58,9 +59,7 @@ class Session extends EventEmitter {
} }
post(method, params, callback) { post(method, params, callback) {
if (typeof method !== 'string') { validateString(method, 'method');
throw new ERR_INVALID_ARG_TYPE('method', 'string', method);
}
if (!callback && util.isFunction(params)) { if (!callback && util.isFunction(params)) {
callback = params; callback = params;
params = null; params = null;

View File

@ -14,6 +14,7 @@ const {
ERR_MISSING_ARGS ERR_MISSING_ARGS
} }
} = require('internal/errors'); } = require('internal/errors');
const { validateString } = require('internal/validators');
const EventEmitter = require('events'); const EventEmitter = require('events');
const net = require('net'); const net = require('net');
const dgram = require('dgram'); const dgram = require('dgram');
@ -318,9 +319,7 @@ ChildProcess.prototype.spawn = function(options) {
options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd);
} }
if (typeof options.file !== 'string') { validateString(options.file, 'options.file');
throw new ERR_INVALID_ARG_TYPE('options.file', 'string', options.file);
}
this.spawnfile = options.file; this.spawnfile = options.file;
if (Array.isArray(options.args)) if (Array.isArray(options.args))

View File

@ -10,6 +10,7 @@ const {
ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_TYPE,
ERR_INVALID_OPT_VALUE ERR_INVALID_OPT_VALUE
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { const {
getDefaultEncoding, getDefaultEncoding,
@ -83,9 +84,7 @@ function createCipherBase(cipher, credential, options, decipher, iv) {
} }
function createCipher(cipher, password, options, decipher) { function createCipher(cipher, password, options, decipher) {
if (typeof cipher !== 'string') validateString(cipher, 'cipher');
throw new ERR_INVALID_ARG_TYPE('cipher', 'string', cipher);
password = toBuf(password); password = toBuf(password);
if (!isArrayBufferView(password)) { if (!isArrayBufferView(password)) {
throw new ERR_INVALID_ARG_TYPE( throw new ERR_INVALID_ARG_TYPE(
@ -99,9 +98,7 @@ function createCipher(cipher, password, options, decipher) {
} }
function createCipherWithIV(cipher, key, options, decipher, iv) { function createCipherWithIV(cipher, key, options, decipher, iv) {
if (typeof cipher !== 'string') validateString(cipher, 'cipher');
throw new ERR_INVALID_ARG_TYPE('cipher', 'string', cipher);
key = toBuf(key); key = toBuf(key);
if (!isArrayBufferView(key)) { if (!isArrayBufferView(key)) {
throw new ERR_INVALID_ARG_TYPE( throw new ERR_INVALID_ARG_TYPE(

View File

@ -6,6 +6,7 @@ const {
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY, ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY,
ERR_INVALID_ARG_TYPE ERR_INVALID_ARG_TYPE
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { isArrayBufferView } = require('internal/util/types'); const { isArrayBufferView } = require('internal/util/types');
const { const {
getDefaultEncoding, getDefaultEncoding,
@ -167,9 +168,7 @@ function ECDH(curve) {
if (!(this instanceof ECDH)) if (!(this instanceof ECDH))
return new ECDH(curve); return new ECDH(curve);
if (typeof curve !== 'string') validateString(curve, 'curve');
throw new ERR_INVALID_ARG_TYPE('curve', 'string', curve);
this._handle = new _ECDH(curve); this._handle = new _ECDH(curve);
} }
@ -200,9 +199,7 @@ ECDH.convertKey = function convertKey(key, curve, inEnc, outEnc, format) {
); );
} }
if (typeof curve !== 'string') { validateString(curve, 'curve');
throw new ERR_INVALID_ARG_TYPE('curve', 'string', curve);
}
const encoding = getDefaultEncoding(); const encoding = getDefaultEncoding();
inEnc = inEnc || encoding; inEnc = inEnc || encoding;

View File

@ -18,6 +18,7 @@ const {
ERR_CRYPTO_HASH_UPDATE_FAILED, ERR_CRYPTO_HASH_UPDATE_FAILED,
ERR_INVALID_ARG_TYPE ERR_INVALID_ARG_TYPE
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { inherits } = require('util'); const { inherits } = require('util');
const { normalizeEncoding } = require('internal/util'); const { normalizeEncoding } = require('internal/util');
const { isArrayBufferView } = require('internal/util/types'); const { isArrayBufferView } = require('internal/util/types');
@ -28,8 +29,7 @@ const kFinalized = Symbol('finalized');
function Hash(algorithm, options) { function Hash(algorithm, options) {
if (!(this instanceof Hash)) if (!(this instanceof Hash))
return new Hash(algorithm, options); return new Hash(algorithm, options);
if (typeof algorithm !== 'string') validateString(algorithm, 'algorithm');
throw new ERR_INVALID_ARG_TYPE('algorithm', 'string', algorithm);
this._handle = new _Hash(algorithm); this._handle = new _Hash(algorithm);
this[kState] = { this[kState] = {
[kFinalized]: false [kFinalized]: false
@ -83,8 +83,7 @@ Hash.prototype.digest = function digest(outputEncoding) {
function Hmac(hmac, key, options) { function Hmac(hmac, key, options) {
if (!(this instanceof Hmac)) if (!(this instanceof Hmac))
return new Hmac(hmac, key, options); return new Hmac(hmac, key, options);
if (typeof hmac !== 'string') validateString(hmac, 'hmac');
throw new ERR_INVALID_ARG_TYPE('hmac', 'string', hmac);
if (typeof key !== 'string' && !isArrayBufferView(key)) { if (typeof key !== 'string' && !isArrayBufferView(key)) {
throw new ERR_INVALID_ARG_TYPE('key', throw new ERR_INVALID_ARG_TYPE('key',
['string', 'TypedArray', 'DataView'], key); ['string', 'TypedArray', 'DataView'], key);

View File

@ -2,9 +2,9 @@
const { const {
ERR_CRYPTO_SIGN_KEY_REQUIRED, ERR_CRYPTO_SIGN_KEY_REQUIRED,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_OPT_VALUE ERR_INVALID_OPT_VALUE
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { const {
Sign: _Sign, Sign: _Sign,
Verify: _Verify Verify: _Verify
@ -24,8 +24,7 @@ const { inherits } = require('util');
function Sign(algorithm, options) { function Sign(algorithm, options) {
if (!(this instanceof Sign)) if (!(this instanceof Sign))
return new Sign(algorithm, options); return new Sign(algorithm, options);
if (typeof algorithm !== 'string') validateString(algorithm, 'algorithm');
throw new ERR_INVALID_ARG_TYPE('algorithm', 'string', algorithm);
this._handle = new _Sign(); this._handle = new _Sign();
this._handle.init(algorithm); this._handle.init(algorithm);
@ -94,8 +93,7 @@ Sign.prototype.sign = function sign(options, encoding) {
function Verify(algorithm, options) { function Verify(algorithm, options) {
if (!(this instanceof Verify)) if (!(this instanceof Verify))
return new Verify(algorithm, options); return new Verify(algorithm, options);
if (typeof algorithm !== 'string') validateString(algorithm, 'algorithm');
throw new ERR_INVALID_ARG_TYPE('algorithm', 'string', algorithm);
this._handle = new _Verify(); this._handle = new _Verify();
this._handle.init(algorithm); this._handle.init(algorithm);

View File

@ -17,6 +17,7 @@ const {
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH,
ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_TYPE,
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { Buffer } = require('buffer'); const { Buffer } = require('buffer');
const { const {
cachedResult, cachedResult,
@ -53,9 +54,7 @@ const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes()));
const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves())); const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
function setEngine(id, flags) { function setEngine(id, flags) {
if (typeof id !== 'string') validateString(id, 'id');
throw new ERR_INVALID_ARG_TYPE('id', 'string', id);
if (flags && typeof flags !== 'number') if (flags && typeof flags !== 'number')
throw new ERR_INVALID_ARG_TYPE('flags', 'number', flags); throw new ERR_INVALID_ARG_TYPE('flags', 'number', flags);
flags = flags >>> 0; flags = flags >>> 0;

View File

@ -12,11 +12,11 @@ const {
ERR_HTTP2_NO_SOCKET_MANIPULATION, ERR_HTTP2_NO_SOCKET_MANIPULATION,
ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED,
ERR_HTTP2_STATUS_INVALID, ERR_HTTP2_STATUS_INVALID,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_VALUE,
ERR_INVALID_CALLBACK, ERR_INVALID_CALLBACK,
ERR_INVALID_HTTP_TOKEN ERR_INVALID_HTTP_TOKEN
} = require('internal/errors').codes; } = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { kSocket } = require('internal/http2/util'); const { kSocket } = require('internal/http2/util');
const kBeginSend = Symbol('begin-send'); const kBeginSend = Symbol('begin-send');
@ -342,8 +342,7 @@ class Http2ServerRequest extends Readable {
} }
set method(method) { set method(method) {
if (typeof method !== 'string') validateString(method, 'method');
throw new ERR_INVALID_ARG_TYPE('method', 'string', method);
if (method.trim() === '') if (method.trim() === '')
throw new ERR_INVALID_ARG_VALUE('method', method); throw new ERR_INVALID_ARG_VALUE('method', method);
@ -482,9 +481,7 @@ class Http2ServerResponse extends Stream {
} }
setTrailer(name, value) { setTrailer(name, value) {
if (typeof name !== 'string') validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
name = name.trim().toLowerCase(); name = name.trim().toLowerCase();
assertValidHeader(name, value); assertValidHeader(name, value);
this[kTrailers][name] = value; this[kTrailers][name] = value;
@ -500,9 +497,7 @@ class Http2ServerResponse extends Stream {
} }
getHeader(name) { getHeader(name) {
if (typeof name !== 'string') validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
name = name.trim().toLowerCase(); name = name.trim().toLowerCase();
return this[kHeaders][name]; return this[kHeaders][name];
} }
@ -516,17 +511,13 @@ class Http2ServerResponse extends Stream {
} }
hasHeader(name) { hasHeader(name) {
if (typeof name !== 'string') validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
name = name.trim().toLowerCase(); name = name.trim().toLowerCase();
return Object.prototype.hasOwnProperty.call(this[kHeaders], name); return Object.prototype.hasOwnProperty.call(this[kHeaders], name);
} }
removeHeader(name) { removeHeader(name) {
if (typeof name !== 'string') validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
if (this[kStream].headersSent) if (this[kStream].headersSent)
throw new ERR_HTTP2_HEADERS_SENT(); throw new ERR_HTTP2_HEADERS_SENT();
@ -535,9 +526,7 @@ class Http2ServerResponse extends Stream {
} }
setHeader(name, value) { setHeader(name, value) {
if (typeof name !== 'string') validateString(name, 'name');
throw new ERR_INVALID_ARG_TYPE('name', 'string', name);
if (this[kStream].headersSent) if (this[kStream].headersSent)
throw new ERR_HTTP2_HEADERS_SENT(); throw new ERR_HTTP2_HEADERS_SENT();

View File

@ -120,11 +120,17 @@ function validateUint32(value, name, positive) {
return value; return value;
} }
function validateString(value, name) {
if (typeof value !== 'string')
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
}
module.exports = { module.exports = {
isInt32, isInt32,
isUint32, isUint32,
validateMode, validateMode,
validateInteger, validateInteger,
validateInt32, validateInt32,
validateUint32 validateUint32,
validateString
}; };

View File

@ -75,7 +75,7 @@ const {
ERR_SOCKET_BAD_PORT, ERR_SOCKET_BAD_PORT,
ERR_SOCKET_CLOSED ERR_SOCKET_CLOSED
} = errors.codes; } = errors.codes;
const { validateInt32 } = require('internal/validators'); const { validateInt32, validateString } = require('internal/validators');
const kLastWriteQueueSize = Symbol('lastWriteQueueSize'); const kLastWriteQueueSize = Symbol('lastWriteQueueSize');
// Lazy loaded to improve startup performance. // Lazy loaded to improve startup performance.
@ -980,9 +980,7 @@ Socket.prototype.connect = function(...args) {
this.writable = true; this.writable = true;
if (pipe) { if (pipe) {
if (typeof path !== 'string') { validateString(path, 'options.path');
throw new ERR_INVALID_ARG_TYPE('options.path', 'string', path);
}
defaultTriggerAsyncIdScope( defaultTriggerAsyncIdScope(
this[async_id_symbol], internalConnect, this, path this[async_id_symbol], internalConnect, this, path
); );