diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 0f1bcb00b1c304..493e0a564e50d7 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -22,11 +22,9 @@ 'use strict'; const { - Object: { - setPrototypeOf: ObjectSetPrototypeOf, - keys: ObjectKeys, - values: ObjectValues - } + ObjectKeys, + ObjectSetPrototypeOf, + ObjectValues, } = primordials; const net = require('net'); diff --git a/lib/_http_client.js b/lib/_http_client.js index 3c54358b160221..4628561170cc84 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -21,7 +21,11 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectKeys, + ObjectSetPrototypeOf, +} = primordials; const net = require('net'); const url = require('url'); @@ -108,7 +112,7 @@ function ClientRequest(input, options, cb) { cb = options; options = input || {}; } else { - options = Object.assign(input || {}, options); + options = ObjectAssign(input || {}, options); } let agent = options.agent; @@ -217,7 +221,7 @@ function ClientRequest(input, options, cb) { const headersArray = Array.isArray(options.headers); if (!headersArray) { if (options.headers) { - const keys = Object.keys(options.headers); + const keys = ObjectKeys(options.headers); for (let i = 0; i < keys.length; i++) { const key = keys[i]; this.setHeader(key, options.headers[key]); @@ -296,8 +300,8 @@ function ClientRequest(input, options, cb) { this._deferToConnect(null, null, () => this._flush()); } -Object.setPrototypeOf(ClientRequest.prototype, OutgoingMessage.prototype); -Object.setPrototypeOf(ClientRequest, OutgoingMessage); +ObjectSetPrototypeOf(ClientRequest.prototype, OutgoingMessage.prototype); +ObjectSetPrototypeOf(ClientRequest, OutgoingMessage); ClientRequest.prototype._finish = function _finish() { DTRACE_HTTP_CLIENT_REQUEST(this, this.connection); diff --git a/lib/_http_common.js b/lib/_http_common.js index 7e58df7f3f3bfa..7ba81e0cd5e5c6 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -21,7 +21,9 @@ 'use strict'; -const { Math } = primordials; +const { + MathMin, +} = primordials; const { setImmediate } = require('timers'); const { getOptionValue } = require('internal/options'); @@ -100,7 +102,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, // If parser.maxHeaderPairs <= 0 assume that there's no limit. if (parser.maxHeaderPairs > 0) - n = Math.min(n, parser.maxHeaderPairs); + n = MathMin(n, parser.maxHeaderPairs); incoming._addHeaderLines(headers, n); diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 8f4c05c5fe5919..5bccb61afceff9 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const Stream = require('stream'); @@ -81,8 +83,8 @@ function IncomingMessage(socket) { // read by the user, so there's no point continuing to handle it. this._dumped = false; } -Object.setPrototypeOf(IncomingMessage.prototype, Stream.Readable.prototype); -Object.setPrototypeOf(IncomingMessage, Stream.Readable); +ObjectSetPrototypeOf(IncomingMessage.prototype, Stream.Readable.prototype); +ObjectSetPrototypeOf(IncomingMessage, Stream.Readable); IncomingMessage.prototype.setTimeout = function setTimeout(msecs, callback) { if (callback) diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index bbcc83f89e9960..460539e766b2c0 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -21,7 +21,13 @@ 'use strict'; -const { Object, ObjectPrototype } = primordials; +const { + ObjectCreate, + ObjectDefineProperty, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ObjectSetPrototypeOf, +} = primordials; const { getDefaultHighWaterMark } = require('internal/streams/state'); const assert = require('internal/assert'); @@ -109,10 +115,10 @@ function OutgoingMessage() { this._onPendingData = noopPendingOutput; } -Object.setPrototypeOf(OutgoingMessage.prototype, Stream.prototype); -Object.setPrototypeOf(OutgoingMessage, Stream); +ObjectSetPrototypeOf(OutgoingMessage.prototype, Stream.prototype); +ObjectSetPrototypeOf(OutgoingMessage, Stream); -Object.defineProperty(OutgoingMessage.prototype, 'writableFinished', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableFinished', { get() { return ( this.finished && @@ -122,32 +128,32 @@ Object.defineProperty(OutgoingMessage.prototype, 'writableFinished', { } }); -Object.defineProperty(OutgoingMessage.prototype, 'writableObjectMode', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableObjectMode', { get() { return false; } }); -Object.defineProperty(OutgoingMessage.prototype, 'writableLength', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableLength', { get() { return this.outputSize + (this.socket ? this.socket.writableLength : 0); } }); -Object.defineProperty(OutgoingMessage.prototype, 'writableHighWaterMark', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableHighWaterMark', { get() { return this.socket ? this.socket.writableHighWaterMark : HIGH_WATER_MARK; } }); -Object.defineProperty(OutgoingMessage.prototype, 'writableCorked', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableCorked', { get() { const corked = this.socket ? this.socket.writableCorked : 0; return corked + this[kCorked]; } }); -Object.defineProperty(OutgoingMessage.prototype, '_headers', { +ObjectDefineProperty(OutgoingMessage.prototype, '_headers', { get: internalUtil.deprecate(function() { return this.getHeaders(); }, 'OutgoingMessage.prototype._headers is deprecated', 'DEP0066'), @@ -155,8 +161,8 @@ Object.defineProperty(OutgoingMessage.prototype, '_headers', { if (val == null) { this[kOutHeaders] = null; } else if (typeof val === 'object') { - const headers = this[kOutHeaders] = Object.create(null); - const keys = Object.keys(val); + const headers = this[kOutHeaders] = ObjectCreate(null); + const keys = ObjectKeys(val); for (var i = 0; i < keys.length; ++i) { const name = keys[i]; headers[name.toLowerCase()] = [name, val[name]]; @@ -165,12 +171,12 @@ Object.defineProperty(OutgoingMessage.prototype, '_headers', { }, 'OutgoingMessage.prototype._headers is deprecated', 'DEP0066') }); -Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { +ObjectDefineProperty(OutgoingMessage.prototype, '_headerNames', { get: internalUtil.deprecate(function() { const headers = this[kOutHeaders]; if (headers !== null) { - const out = Object.create(null); - const keys = Object.keys(headers); + const out = ObjectCreate(null); + const keys = ObjectKeys(headers); for (var i = 0; i < keys.length; ++i) { const key = keys[i]; const val = headers[key][0]; @@ -185,7 +191,7 @@ Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { const headers = this[kOutHeaders]; if (!headers) return; - const keys = Object.keys(val); + const keys = ObjectKeys(val); for (var i = 0; i < keys.length; ++i) { const header = headers[keys[i]]; if (header) @@ -205,7 +211,7 @@ OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { const headers = {}; if (headersMap !== null) { - const keys = Object.keys(headersMap); + const keys = ObjectKeys(headersMap); for (var i = 0, l = keys.length; i < l; i++) { const key = keys[i]; headers[headersMap[key][0]] = headersMap[key][1]; @@ -350,7 +356,7 @@ function _storeHeader(firstLine, headers) { } } else { for (const key in headers) { - if (ObjectPrototype.hasOwnProperty(headers, key)) { + if (ObjectPrototypeHasOwnProperty(headers, key)) { processHeader(this, state, key, headers[key], true); } } @@ -511,7 +517,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) { let headers = this[kOutHeaders]; if (headers === null) - this[kOutHeaders] = headers = Object.create(null); + this[kOutHeaders] = headers = ObjectCreate(null); headers[name.toLowerCase()] = [name, value]; }; @@ -531,16 +537,16 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) { // Returns an array of the names of the current outgoing headers. OutgoingMessage.prototype.getHeaderNames = function getHeaderNames() { - return this[kOutHeaders] !== null ? Object.keys(this[kOutHeaders]) : []; + return this[kOutHeaders] !== null ? ObjectKeys(this[kOutHeaders]) : []; }; // Returns a shallow copy of the current outgoing headers. OutgoingMessage.prototype.getHeaders = function getHeaders() { const headers = this[kOutHeaders]; - const ret = Object.create(null); + const ret = ObjectCreate(null); if (headers) { - const keys = Object.keys(headers); + const keys = ObjectKeys(headers); for (var i = 0; i < keys.length; ++i) { const key = keys[i]; const val = headers[key][1]; @@ -592,13 +598,13 @@ OutgoingMessage.prototype._implicitHeader = function _implicitHeader() { this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_implicitHeader()')); }; -Object.defineProperty(OutgoingMessage.prototype, 'headersSent', { +ObjectDefineProperty(OutgoingMessage.prototype, 'headersSent', { configurable: true, enumerable: true, get: function() { return !!this._header; } }); -Object.defineProperty(OutgoingMessage.prototype, 'writableEnded', { +ObjectDefineProperty(OutgoingMessage.prototype, 'writableEnded', { get: function() { return this.finished; } }); @@ -679,7 +685,7 @@ function connectionCorkNT(conn) { OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { this._trailer = ''; - const keys = Object.keys(headers); + const keys = ObjectKeys(headers); const isArray = Array.isArray(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { diff --git a/lib/_http_server.js b/lib/_http_server.js index 0638820a16c939..4fbd3c00008c42 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -22,10 +22,8 @@ 'use strict'; const { - Object: { - setPrototypeOf: ObjectSetPrototypeOf, - keys: ObjectKeys, - } + ObjectKeys, + ObjectSetPrototypeOf, } = primordials; const net = require('net'); @@ -265,7 +263,7 @@ function writeHead(statusCode, reason, obj) { let k; if (obj) { const keys = ObjectKeys(obj); - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { k = keys[i]; if (k) this.setHeader(k, obj[k]); } diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js index 858dc938f01cd1..572e6da94d8a6a 100644 --- a/lib/_stream_duplex.js +++ b/lib/_stream_duplex.js @@ -26,19 +26,23 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectKeys, + ObjectSetPrototypeOf, +} = primordials; module.exports = Duplex; const Readable = require('_stream_readable'); const Writable = require('_stream_writable'); -Object.setPrototypeOf(Duplex.prototype, Readable.prototype); -Object.setPrototypeOf(Duplex, Readable); +ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); +ObjectSetPrototypeOf(Duplex, Readable); { // Allow the keys array to be GC'ed. - const keys = Object.keys(Writable.prototype); + const keys = ObjectKeys(Writable.prototype); for (let v = 0; v < keys.length; v++) { const method = keys[v]; if (!Duplex.prototype[method]) @@ -68,7 +72,7 @@ function Duplex(options) { } } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { +ObjectDefineProperty(Duplex.prototype, 'writableHighWaterMark', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -78,7 +82,7 @@ Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { } }); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { +ObjectDefineProperty(Duplex.prototype, 'writableBuffer', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -88,7 +92,7 @@ Object.defineProperty(Duplex.prototype, 'writableBuffer', { } }); -Object.defineProperty(Duplex.prototype, 'writableLength', { +ObjectDefineProperty(Duplex.prototype, 'writableLength', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -98,7 +102,7 @@ Object.defineProperty(Duplex.prototype, 'writableLength', { } }); -Object.defineProperty(Duplex.prototype, 'writableFinished', { +ObjectDefineProperty(Duplex.prototype, 'writableFinished', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -108,7 +112,7 @@ Object.defineProperty(Duplex.prototype, 'writableFinished', { } }); -Object.defineProperty(Duplex.prototype, 'writableCorked', { +ObjectDefineProperty(Duplex.prototype, 'writableCorked', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -118,7 +122,7 @@ Object.defineProperty(Duplex.prototype, 'writableCorked', { } }); -Object.defineProperty(Duplex.prototype, 'writableEnded', { +ObjectDefineProperty(Duplex.prototype, 'writableEnded', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -143,7 +147,7 @@ function onEndNT(self) { self.end(); } -Object.defineProperty(Duplex.prototype, 'destroyed', { +ObjectDefineProperty(Duplex.prototype, 'destroyed', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js index 205a14b65fe243..279df5ac2d68ca 100644 --- a/lib/_stream_passthrough.js +++ b/lib/_stream_passthrough.js @@ -25,13 +25,15 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; module.exports = PassThrough; const Transform = require('_stream_transform'); -Object.setPrototypeOf(PassThrough.prototype, Transform.prototype); -Object.setPrototypeOf(PassThrough, Transform); +ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); +ObjectSetPrototypeOf(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 1cde902c92206d..3345dcd09b3978 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -21,7 +21,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; module.exports = Readable; Readable.ReadableState = ReadableState; @@ -49,8 +52,8 @@ let StringDecoder; let createReadableStreamAsyncIterator; let from; -Object.setPrototypeOf(Readable.prototype, Stream.prototype); -Object.setPrototypeOf(Readable, Stream); +ObjectSetPrototypeOf(Readable.prototype, Stream.prototype); +ObjectSetPrototypeOf(Readable, Stream); const { errorOrDestroy } = destroyImpl; const kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; @@ -176,7 +179,7 @@ function Readable(options) { Stream.call(this); } -Object.defineProperty(Readable.prototype, 'destroyed', { +ObjectDefineProperty(Readable.prototype, 'destroyed', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -200,7 +203,7 @@ Object.defineProperty(Readable.prototype, 'destroyed', { } }); -Object.defineProperty(Readable.prototype, 'readableEnded', { +ObjectDefineProperty(Readable.prototype, 'readableEnded', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -1074,7 +1077,7 @@ Readable.prototype[Symbol.asyncIterator] = function() { return createReadableStreamAsyncIterator(this); }; -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { +ObjectDefineProperty(Readable.prototype, 'readableHighWaterMark', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -1084,7 +1087,7 @@ Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { } }); -Object.defineProperty(Readable.prototype, 'readableBuffer', { +ObjectDefineProperty(Readable.prototype, 'readableBuffer', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -1094,7 +1097,7 @@ Object.defineProperty(Readable.prototype, 'readableBuffer', { } }); -Object.defineProperty(Readable.prototype, 'readableFlowing', { +ObjectDefineProperty(Readable.prototype, 'readableFlowing', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -1112,7 +1115,7 @@ Object.defineProperty(Readable.prototype, 'readableFlowing', { // Exposed for testing purposes only. Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { +ObjectDefineProperty(Readable.prototype, 'readableLength', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -1122,14 +1125,14 @@ Object.defineProperty(Readable.prototype, 'readableLength', { } }); -Object.defineProperty(Readable.prototype, 'readableObjectMode', { +ObjectDefineProperty(Readable.prototype, 'readableObjectMode', { enumerable: false, get() { return this._readableState ? this._readableState.objectMode : false; } }); -Object.defineProperty(Readable.prototype, 'readableEncoding', { +ObjectDefineProperty(Readable.prototype, 'readableEncoding', { enumerable: false, get() { return this._readableState ? this._readableState.encoding : null; diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index b4fffaa98891cd..cb4aae2e6d18f4 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -63,7 +63,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; module.exports = Transform; const { @@ -73,8 +75,8 @@ const { ERR_TRANSFORM_WITH_LENGTH_0 } = require('internal/errors').codes; const Duplex = require('_stream_duplex'); -Object.setPrototypeOf(Transform.prototype, Duplex.prototype); -Object.setPrototypeOf(Transform, Duplex); +ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); +ObjectSetPrototypeOf(Transform, Duplex); function afterTransform(er, data) { diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index aaecb3a383e631..7a21b16f3244b1 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -25,7 +25,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; module.exports = Writable; Writable.WritableState = WritableState; @@ -51,8 +54,8 @@ const { const { errorOrDestroy } = destroyImpl; -Object.setPrototypeOf(Writable.prototype, Stream.prototype); -Object.setPrototypeOf(Writable, Stream); +ObjectSetPrototypeOf(Writable.prototype, Stream.prototype); +ObjectSetPrototypeOf(Writable, Stream); function nop() {} @@ -181,7 +184,7 @@ WritableState.prototype.getBuffer = function getBuffer() { return out; }; -Object.defineProperty(WritableState.prototype, 'buffer', { +ObjectDefineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + @@ -193,7 +196,7 @@ Object.defineProperty(WritableState.prototype, 'buffer', { var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance) { realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { + ObjectDefineProperty(Writable, Symbol.hasInstance, { value: function(object) { if (realHasInstance.call(this, object)) return true; @@ -340,7 +343,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { return this; }; -Object.defineProperty(Writable.prototype, 'writableBuffer', { +ObjectDefineProperty(Writable.prototype, 'writableBuffer', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -359,7 +362,7 @@ function decodeChunk(state, chunk, encoding) { return chunk; } -Object.defineProperty(Writable.prototype, 'writableEnded', { +ObjectDefineProperty(Writable.prototype, 'writableEnded', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -369,7 +372,7 @@ Object.defineProperty(Writable.prototype, 'writableEnded', { } }); -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { +ObjectDefineProperty(Writable.prototype, 'writableHighWaterMark', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -379,7 +382,7 @@ Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { } }); -Object.defineProperty(Writable.prototype, 'writableCorked', { +ObjectDefineProperty(Writable.prototype, 'writableCorked', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -639,7 +642,7 @@ Writable.prototype.end = function(chunk, encoding, cb) { return this; }; -Object.defineProperty(Writable.prototype, 'writableLength', { +ObjectDefineProperty(Writable.prototype, 'writableLength', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -730,7 +733,7 @@ function onCorkedFinish(corkReq, state, err) { state.corkedRequestsFree.next = corkReq; } -Object.defineProperty(Writable.prototype, 'destroyed', { +ObjectDefineProperty(Writable.prototype, 'destroyed', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -754,14 +757,14 @@ Object.defineProperty(Writable.prototype, 'destroyed', { } }); -Object.defineProperty(Writable.prototype, 'writableObjectMode', { +ObjectDefineProperty(Writable.prototype, 'writableObjectMode', { enumerable: false, get() { return this._writableState ? this._writableState.objectMode : false; } }); -Object.defineProperty(Writable.prototype, 'writableFinished', { +ObjectDefineProperty(Writable.prototype, 'writableFinished', { // Making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 981503e6e96658..13ff850c994146 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, +} = primordials; const { parseCertString } = require('internal/tls'); const { isArrayBufferView } = require('internal/util/types'); @@ -314,7 +316,7 @@ exports.translatePeerCertificate = function translatePeerCertificate(c) { if (c.subject != null) c.subject = parseCertString(c.subject); if (c.infoAccess != null) { const info = c.infoAccess; - c.infoAccess = Object.create(null); + c.infoAccess = ObjectCreate(null); // XXX: More key validation? info.replace(/([^\n:]*):([^\n]*)(?:\n|$)/g, (all, key, val) => { diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 388349d019fa0a..7e52fbcfa2b187 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -21,7 +21,11 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const { assertCrypto, @@ -504,8 +508,8 @@ function TLSSocket(socket, opts) { // Read on next tick so the caller has a chance to setup listeners process.nextTick(initRead, this, socket); } -Object.setPrototypeOf(TLSSocket.prototype, net.Socket.prototype); -Object.setPrototypeOf(TLSSocket, net.Socket); +ObjectSetPrototypeOf(TLSSocket.prototype, net.Socket.prototype); +ObjectSetPrototypeOf(TLSSocket, net.Socket); exports.TLSSocket = TLSSocket; const proxiedMethods = [ @@ -599,7 +603,7 @@ TLSSocket.prototype._wrapHandle = function(wrap) { // This eliminates a cyclic reference to TLSWrap // Ref: https://github.com/nodejs/node/commit/f7620fb96d339f704932f9bb9a0dceb9952df2d4 function defineHandleReading(socket, handle) { - Object.defineProperty(handle, 'reading', { + ObjectDefineProperty(handle, 'reading', { get: () => { return socket[kRes].reading; }, @@ -1187,8 +1191,8 @@ function Server(options, listener) { this[kEnableTrace] = options.enableTrace; } -Object.setPrototypeOf(Server.prototype, net.Server.prototype); -Object.setPrototypeOf(Server, net.Server); +ObjectSetPrototypeOf(Server.prototype, net.Server.prototype); +ObjectSetPrototypeOf(Server, net.Server); exports.Server = Server; exports.createServer = function createServer(options, listener) { return new Server(options, listener); @@ -1430,9 +1434,9 @@ function normalizeConnectArgs(listArgs) { // the host/port/path args that it knows about, not the tls options. // This means that options.host overrides a host arg. if (listArgs[1] !== null && typeof listArgs[1] === 'object') { - Object.assign(options, listArgs[1]); + ObjectAssign(options, listArgs[1]); } else if (listArgs[2] !== null && typeof listArgs[2] === 'object') { - Object.assign(options, listArgs[2]); + ObjectAssign(options, listArgs[2]); } return cb ? [options, cb] : [options]; diff --git a/lib/assert.js b/lib/assert.js index d4068fc96831c1..c975e1d236ef06 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -20,7 +20,11 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectIs, + ObjectKeys, +} = primordials; const { Buffer } = require('buffer'); const { @@ -493,7 +497,7 @@ assert.strictEqual = function strictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } - if (!Object.is(actual, expected)) { + if (!ObjectIs(actual, expected)) { innerFail({ actual, expected, @@ -508,7 +512,7 @@ assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } - if (Object.is(actual, expected)) { + if (ObjectIs(actual, expected)) { innerFail({ actual, expected, @@ -596,7 +600,7 @@ function expectedException(actual, expected, message, fn) { } // Handle validation objects. - const keys = Object.keys(expected); + const keys = ObjectKeys(expected); // Special handle errors to make sure the name and the message are compared // as well. if (expected instanceof Error) { @@ -845,7 +849,7 @@ assert.ifError = function ifError(err) { function strict(...args) { innerOk(strict, args.length, ...args); } -assert.strict = Object.assign(strict, assert, { +assert.strict = ObjectAssign(strict, assert, { equal: assert.strictEqual, deepEqual: assert.deepStrictEqual, notEqual: assert.notStrictEqual, diff --git a/lib/async_hooks.js b/lib/async_hooks.js index c18a902c2ace84..a567e1599f7eea 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -1,6 +1,8 @@ 'use strict'; -const { Reflect } = primordials; +const { + ReflectApply, +} = primordials; const { ERR_ASYNC_CALLBACK, @@ -171,7 +173,7 @@ class AsyncResource { try { if (thisArg === undefined) return fn(...args); - return Reflect.apply(fn, thisArg, args); + return ReflectApply(fn, thisArg, args); } finally { if (hasAsyncIdStack()) emitAfter(asyncId); diff --git a/lib/buffer.js b/lib/buffer.js index a751677a7344ea..6c70cd61c8a947 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -22,17 +22,13 @@ 'use strict'; const { - Object: { - defineProperties: ObjectDefineProperties, - defineProperty: ObjectDefineProperty, - setPrototypeOf: ObjectSetPrototypeOf, - create: ObjectCreate - }, - Math: { - floor: MathFloor, - trunc: MathTrunc, - min: MathMin - } + MathFloor, + MathMin, + MathTrunc, + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectSetPrototypeOf, } = primordials; const { diff --git a/lib/child_process.js b/lib/child_process.js index 0a98f84467532f..e574b6b85ab94b 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -21,7 +21,11 @@ 'use strict'; -const { Object, ObjectPrototype } = primordials; +const { + ObjectAssign, + ObjectDefineProperty, + ObjectPrototypeHasOwnProperty, +} = primordials; const { promisify, @@ -170,7 +174,7 @@ const customPromiseExecFunction = (orig) => { }; }; -Object.defineProperty(exec, promisify.custom, { +ObjectDefineProperty(exec, promisify.custom, { enumerable: false, value: customPromiseExecFunction(exec) }); @@ -389,7 +393,7 @@ function execFile(file /* , args, options, callback */) { return child; } -Object.defineProperty(execFile, promisify.custom, { +ObjectDefineProperty(execFile, promisify.custom, { enumerable: false, value: customPromiseExecFunction(execFile) }); @@ -509,7 +513,7 @@ function normalizeSpawnArguments(file, args, options) { // process.env.NODE_V8_COVERAGE always propagates, making it possible to // collect coverage for programs that spawn with white-listed environment. if (process.env.NODE_V8_COVERAGE && - !ObjectPrototype.hasOwnProperty(options.env || {}, 'NODE_V8_COVERAGE')) { + !ObjectPrototypeHasOwnProperty(options.env || {}, 'NODE_V8_COVERAGE')) { env.NODE_V8_COVERAGE = process.env.NODE_V8_COVERAGE; } @@ -622,7 +626,7 @@ function checkExecSyncError(ret, args, cmd) { err = new Error(msg); } if (err) { - Object.assign(err, ret); + ObjectAssign(err, ret); } return err; } diff --git a/lib/constants.js b/lib/constants.js index 77341c064640f1..cd510f7a37b4ed 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -21,18 +21,21 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectFreeze, +} = primordials; // This module is deprecated in documentation only. Users should be directed // towards using the specific constants exposed by the individual modules on // which they are most relevant. // Deprecation Code: DEP0008 const constants = internalBinding('constants'); -Object.assign(exports, - constants.os.dlopen, - constants.os.errno, - constants.os.priority, - constants.os.signals, - constants.fs, - constants.crypto); -Object.freeze(exports); +ObjectAssign(exports, + constants.os.dlopen, + constants.os.errno, + constants.os.priority, + constants.os.signals, + constants.fs, + constants.crypto); +ObjectFreeze(exports); diff --git a/lib/crypto.js b/lib/crypto.js index 6bfa8319c1b2b5..e2d1875d8d0c8b 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -24,7 +24,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperties, +} = primordials; const { assertCrypto, @@ -220,7 +222,7 @@ function getFipsForced() { return 1; } -Object.defineProperties(module.exports, { +ObjectDefineProperties(module.exports, { createCipher: { enumerable: false, value: deprecate(createCipher, diff --git a/lib/dgram.js b/lib/dgram.js index 0812b3213d1007..c0fe57ea5874f9 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -21,7 +21,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const errors = require('internal/errors'); const { @@ -121,8 +124,8 @@ function Socket(type, listener) { sendBufferSize }; } -Object.setPrototypeOf(Socket.prototype, EventEmitter.prototype); -Object.setPrototypeOf(Socket, EventEmitter); +ObjectSetPrototypeOf(Socket.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(Socket, EventEmitter); function createSocket(type, listener) { @@ -965,7 +968,7 @@ Socket.prototype.getSendBufferSize = function() { // Deprecated private APIs. -Object.defineProperty(Socket.prototype, '_handle', { +ObjectDefineProperty(Socket.prototype, '_handle', { get: deprecate(function() { return this[kStateSymbol].handle; }, 'Socket.prototype._handle is deprecated', 'DEP0112'), @@ -975,7 +978,7 @@ Object.defineProperty(Socket.prototype, '_handle', { }); -Object.defineProperty(Socket.prototype, '_receiving', { +ObjectDefineProperty(Socket.prototype, '_receiving', { get: deprecate(function() { return this[kStateSymbol].receiving; }, 'Socket.prototype._receiving is deprecated', 'DEP0112'), @@ -985,7 +988,7 @@ Object.defineProperty(Socket.prototype, '_receiving', { }); -Object.defineProperty(Socket.prototype, '_bindState', { +ObjectDefineProperty(Socket.prototype, '_bindState', { get: deprecate(function() { return this[kStateSymbol].bindState; }, 'Socket.prototype._bindState is deprecated', 'DEP0112'), @@ -995,7 +998,7 @@ Object.defineProperty(Socket.prototype, '_bindState', { }); -Object.defineProperty(Socket.prototype, '_queue', { +ObjectDefineProperty(Socket.prototype, '_queue', { get: deprecate(function() { return this[kStateSymbol].queue; }, 'Socket.prototype._queue is deprecated', 'DEP0112'), @@ -1005,7 +1008,7 @@ Object.defineProperty(Socket.prototype, '_queue', { }); -Object.defineProperty(Socket.prototype, '_reuseAddr', { +ObjectDefineProperty(Socket.prototype, '_reuseAddr', { get: deprecate(function() { return this[kStateSymbol].reuseAddr; }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112'), @@ -1027,7 +1030,7 @@ Socket.prototype._stopReceiving = deprecate(function() { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. -Object.defineProperty(UDP.prototype, 'owner', { +ObjectDefineProperty(UDP.prototype, 'owner', { get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); diff --git a/lib/dns.js b/lib/dns.js index 2a4dd15c5edeac..8a6c7456babbd0 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -21,7 +21,11 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, +} = primordials; const cares = internalBinding('cares_wrap'); const { toASCII } = require('internal/idna'); @@ -152,8 +156,8 @@ function lookup(hostname, options, callback) { return req; } -Object.defineProperty(lookup, customPromisifyArgs, - { value: ['address', 'family'], enumerable: false }); +ObjectDefineProperty(lookup, customPromisifyArgs, + { value: ['address', 'family'], enumerable: false }); function onlookupservice(err, hostname, service) { @@ -190,8 +194,8 @@ function lookupService(address, port, callback) { return req; } -Object.defineProperty(lookupService, customPromisifyArgs, - { value: ['hostname', 'service'], enumerable: false }); +ObjectDefineProperty(lookupService, customPromisifyArgs, + { value: ['hostname', 'service'], enumerable: false }); function onresolve(err, result, ttls) { @@ -227,11 +231,11 @@ function resolver(bindingName) { if (err) throw dnsException(err, bindingName, name); return req; } - Object.defineProperty(query, 'name', { value: bindingName }); + ObjectDefineProperty(query, 'name', { value: bindingName }); return query; } -const resolveMap = Object.create(null); +const resolveMap = ObjectCreate(null); Resolver.prototype.resolveAny = resolveMap.ANY = resolver('queryAny'); Resolver.prototype.resolve4 = resolveMap.A = resolver('queryA'); Resolver.prototype.resolve6 = resolveMap.AAAA = resolver('queryAaaa'); @@ -316,7 +320,7 @@ module.exports = { bindDefaultResolver(module.exports, getDefaultResolver()); -Object.defineProperties(module.exports, { +ObjectDefineProperties(module.exports, { promises: { configurable: true, enumerable: true, diff --git a/lib/domain.js b/lib/domain.js index 3a5d7614c4f4cb..787dbbd1adb7c2 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -26,7 +26,10 @@ // No new pull requests targeting this module will be accepted // unless they address existing, critical bugs. -const { Object, Reflect } = primordials; +const { + ObjectDefineProperty, + ReflectApply, +} = primordials; const EventEmitter = require('events'); const { @@ -43,7 +46,7 @@ const { WeakReference } = internalBinding('util'); // Overwrite process.domain with a getter/setter that will allow for more // effective optimizations const _domain = [null]; -Object.defineProperty(process, 'domain', { +ObjectDefineProperty(process, 'domain', { enumerable: true, get: function() { return _domain[0]; @@ -59,7 +62,7 @@ const asyncHook = createHook({ if (process.domain !== null && process.domain !== undefined) { // If this operation is created while in a domain, let's mark it pairing.set(asyncId, process.domain[kWeak]); - Object.defineProperty(resource, 'domain', { + ObjectDefineProperty(resource, 'domain', { configurable: true, enumerable: false, value: process.domain, @@ -127,7 +130,7 @@ function topLevelDomainCallback(cb, ...args) { if (domain) domain.enter(); - const ret = Reflect.apply(cb, this, args); + const ret = ReflectApply(cb, this, args); if (domain) domain.exit(); @@ -207,7 +210,7 @@ Domain.prototype._errorHandler = function(er) { let caught = false; if ((typeof er === 'object' && er !== null) || typeof er === 'function') { - Object.defineProperty(er, 'domain', { + ObjectDefineProperty(er, 'domain', { configurable: true, enumerable: false, value: this, @@ -329,7 +332,7 @@ Domain.prototype.add = function(ee) { } } - Object.defineProperty(ee, 'domain', { + ObjectDefineProperty(ee, 'domain', { configurable: true, enumerable: false, value: this, @@ -373,7 +376,7 @@ function intercepted(_this, self, cb, fnargs) { const er = fnargs[0]; er.domainBound = cb; er.domainThrown = false; - Object.defineProperty(er, 'domain', { + ObjectDefineProperty(er, 'domain', { configurable: true, enumerable: false, value: self, @@ -432,7 +435,7 @@ Domain.prototype.bind = function(cb) { return bound(this, self, cb, arguments); } - Object.defineProperty(runBound, 'domain', { + ObjectDefineProperty(runBound, 'domain', { configurable: true, enumerable: false, value: this, @@ -447,7 +450,7 @@ EventEmitter.usingDomains = true; const eventInit = EventEmitter.init; EventEmitter.init = function() { - Object.defineProperty(this, 'domain', { + ObjectDefineProperty(this, 'domain', { configurable: true, enumerable: false, value: null, @@ -472,7 +475,7 @@ EventEmitter.prototype.emit = function(...args) { // handler, there's no active domain or this is process if (shouldEmitError || domain === null || domain === undefined || this === process) { - return Reflect.apply(eventEmit, this, args); + return ReflectApply(eventEmit, this, args); } if (type === 'error') { @@ -481,7 +484,7 @@ EventEmitter.prototype.emit = function(...args) { if (typeof er === 'object') { er.domainEmitter = this; - Object.defineProperty(er, 'domain', { + ObjectDefineProperty(er, 'domain', { configurable: true, enumerable: false, value: domain, @@ -495,7 +498,7 @@ EventEmitter.prototype.emit = function(...args) { } domain.enter(); - const ret = Reflect.apply(eventEmit, this, args); + const ret = ReflectApply(eventEmit, this, args); domain.exit(); return ret; diff --git a/lib/events.js b/lib/events.js index a5f978d731b5bf..8e16904cc8cbf4 100644 --- a/lib/events.js +++ b/lib/events.js @@ -22,19 +22,13 @@ 'use strict'; const { - Math: { - min: MathMin - }, - Object: { - defineProperty: ObjectDefineProperty, - getPrototypeOf: ObjectGetPrototypeOf, - create: ObjectCreate, - keys: ObjectKeys, - }, - Reflect: { - apply: ReflectApply, - ownKeys: ReflectOwnKeys, - } + MathMin, + ObjectCreate, + ObjectDefineProperty, + ObjectGetPrototypeOf, + ObjectKeys, + ReflectApply, + ReflectOwnKeys, } = primordials; let spliceOne; diff --git a/lib/fs.js b/lib/fs.js index 1420e60daaf2f5..2d58e48425c2a8 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -24,7 +24,12 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathMax, + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, +} = primordials; const { fs: constants } = internalBinding('constants'); const { @@ -209,7 +214,7 @@ function exists(path, callback) { } } -Object.defineProperty(exists, internalUtil.promisify.custom, { +ObjectDefineProperty(exists, internalUtil.promisify.custom, { value: (path) => { return new Promise((resolve) => fs.exists(path, resolve)); } @@ -485,8 +490,8 @@ function read(fd, buffer, offset, length, position, callback) { binding.read(fd, buffer, offset, length, position, req); } -Object.defineProperty(read, internalUtil.customPromisifyArgs, - { value: ['bytesRead', 'buffer'], enumerable: false }); +ObjectDefineProperty(read, internalUtil.customPromisifyArgs, + { value: ['bytesRead', 'buffer'], enumerable: false }); function readSync(fd, buffer, offset, length, position) { validateInt32(fd, 'fd', 0); @@ -558,8 +563,8 @@ function write(fd, buffer, offset, length, position, callback) { return binding.writeString(fd, buffer, offset, length, req); } -Object.defineProperty(write, internalUtil.customPromisifyArgs, - { value: ['bytesWritten', 'buffer'], enumerable: false }); +ObjectDefineProperty(write, internalUtil.customPromisifyArgs, + { value: ['bytesWritten', 'buffer'], enumerable: false }); // Usage: // fs.writeSync(fd, buffer[, offset[, length[, position]]]); @@ -612,7 +617,7 @@ function writev(fd, buffers, position, callback) { return binding.writeBuffers(fd, buffers, position, req); } -Object.defineProperty(writev, internalUtil.customPromisifyArgs, { +ObjectDefineProperty(writev, internalUtil.customPromisifyArgs, { value: ['bytesWritten', 'buffer'], enumerable: false }); @@ -706,7 +711,7 @@ function ftruncate(fd, len = 0, callback) { } validateInt32(fd, 'fd', 0); validateInteger(len, 'len'); - len = Math.max(0, len); + len = MathMax(0, len); const req = new FSReqCallback(); req.oncomplete = makeCallback(callback); binding.ftruncate(fd, len, req); @@ -715,7 +720,7 @@ function ftruncate(fd, len = 0, callback) { function ftruncateSync(fd, len = 0) { validateInt32(fd, 'fd', 0); validateInteger(len, 'len'); - len = Math.max(0, len); + len = MathMax(0, len); const ctx = {}; binding.ftruncate(fd, len, undefined, ctx); handleErrorFromBinding(ctx); @@ -1453,7 +1458,7 @@ if (isWindows) { nextPart = function nextPart(p, i) { return p.indexOf('/', i); }; } -const emptyObj = Object.create(null); +const emptyObj = ObjectCreate(null); function realpathSync(p, options) { if (!options) options = emptyObj; @@ -1472,8 +1477,8 @@ function realpathSync(p, options) { return maybeCachedResult; } - const seenLinks = Object.create(null); - const knownHard = Object.create(null); + const seenLinks = ObjectCreate(null); + const knownHard = ObjectCreate(null); const original = p; // Current character position in p @@ -1610,8 +1615,8 @@ function realpath(p, options, callback) { validatePath(p); p = pathModule.resolve(p); - const seenLinks = Object.create(null); - const knownHard = Object.create(null); + const seenLinks = ObjectCreate(null); + const knownHard = ObjectCreate(null); // Current character position in p let pos; @@ -1942,7 +1947,7 @@ module.exports = fs = { _toUnixTimestamp: toUnixTimestamp }; -Object.defineProperties(fs, { +ObjectDefineProperties(fs, { F_OK: { enumerable: true, value: F_OK || 0 }, R_OK: { enumerable: true, value: R_OK || 0 }, W_OK: { enumerable: true, value: W_OK || 0 }, diff --git a/lib/http.js b/lib/http.js index 8582557446397e..55c655763d2647 100644 --- a/lib/http.js +++ b/lib/http.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const httpAgent = require('_http_agent'); const { ClientRequest } = require('_http_client'); @@ -65,7 +67,7 @@ module.exports = { request }; -Object.defineProperty(module.exports, 'maxHeaderSize', { +ObjectDefineProperty(module.exports, 'maxHeaderSize', { configurable: true, enumerable: true, get() { @@ -78,7 +80,7 @@ Object.defineProperty(module.exports, 'maxHeaderSize', { } }); -Object.defineProperty(module.exports, 'globalAgent', { +ObjectDefineProperty(module.exports, 'globalAgent', { configurable: true, enumerable: true, get() { diff --git a/lib/https.js b/lib/https.js index 48f9b42dc95b7e..cc118669e8f517 100644 --- a/lib/https.js +++ b/lib/https.js @@ -21,7 +21,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectSetPrototypeOf, +} = primordials; require('internal/util').assertCrypto(); @@ -80,8 +83,8 @@ function Server(opts, requestListener) { this.maxHeadersCount = null; this.headersTimeout = 40 * 1000; // 40 seconds } -Object.setPrototypeOf(Server.prototype, tls.Server.prototype); -Object.setPrototypeOf(Server, tls.Server); +ObjectSetPrototypeOf(Server.prototype, tls.Server.prototype); +ObjectSetPrototypeOf(Server, tls.Server); Server.prototype.setTimeout = HttpServer.prototype.setTimeout; @@ -159,8 +162,8 @@ function Agent(options) { list: [] }; } -Object.setPrototypeOf(Agent.prototype, HttpAgent.prototype); -Object.setPrototypeOf(Agent, HttpAgent); +ObjectSetPrototypeOf(Agent.prototype, HttpAgent.prototype); +ObjectSetPrototypeOf(Agent, HttpAgent); Agent.prototype.createConnection = createConnection; Agent.prototype.getName = function getName(options) { @@ -302,7 +305,7 @@ function request(...args) { } if (args[0] && typeof args[0] !== 'function') { - Object.assign(options, args.shift()); + ObjectAssign(options, args.shift()); } options._defaultAgent = module.exports.globalAgent; diff --git a/lib/inspector.js b/lib/inspector.js index b6a29f4d747dee..b2bad040ceae79 100644 --- a/lib/inspector.js +++ b/lib/inspector.js @@ -1,6 +1,9 @@ 'use strict'; -const { JSON } = primordials; +const { + JSONParse, + JSONStringify, +} = primordials; const { ERR_INSPECTOR_ALREADY_CONNECTED, @@ -62,7 +65,7 @@ class Session extends EventEmitter { } [onMessageSymbol](message) { - const parsed = JSON.parse(message); + const parsed = JSONParse(message); try { if (parsed.id) { const callback = this[messageCallbacksSymbol].get(parsed.id); @@ -108,7 +111,7 @@ class Session extends EventEmitter { if (callback) { this[messageCallbacksSymbol].set(id, callback); } - this[connectionSymbol].dispatch(JSON.stringify(message)); + this[connectionSymbol].dispatch(JSONStringify(message)); } disconnect() { diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index 0b57bf2cb200c5..69a6d8afac52c4 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -1,6 +1,12 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathMax, + ObjectCreate, + ObjectDefineProperty, + ObjectGetPrototypeOf, + ObjectKeys, +} = primordials; const { inspect } = require('internal/util/inspect'); const { codes: { @@ -31,12 +37,12 @@ const kReadableOperator = { const kMaxShortLength = 12; function copyError(source) { - const keys = Object.keys(source); - const target = Object.create(Object.getPrototypeOf(source)); + const keys = ObjectKeys(source); + const target = ObjectCreate(ObjectGetPrototypeOf(source)); for (const key of keys) { target[key] = source[key]; } - Object.defineProperty(target, 'message', { value: source.message }); + ObjectDefineProperty(target, 'message', { value: source.message }); return target; } @@ -135,7 +141,7 @@ function createErrDiff(actual, expected, operator) { b = expectedLines[expectedLines.length - 1]; } - const maxLines = Math.max(actualLines.length, expectedLines.length); + const maxLines = MathMax(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference. // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) if (maxLines === 0) { @@ -404,7 +410,7 @@ class AssertionError extends Error { Error.stackTraceLimit = limit; this.generatedMessage = !message; - Object.defineProperty(this, 'name', { + ObjectDefineProperty(this, 'name', { value: 'AssertionError [ERR_ASSERTION]', enumerable: false, writable: true, diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 6116712fb7cce6..441b0bfb034ec8 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -1,6 +1,9 @@ 'use strict'; -const { FunctionPrototype, Object } = primordials; +const { + FunctionPrototypeBind, + ObjectDefineProperty, +} = primordials; const { ERR_ASYNC_TYPE, @@ -184,10 +187,10 @@ function emitHook(symbol, asyncId) { } function emitHookFactory(symbol, name) { - const fn = FunctionPrototype.bind(emitHook, undefined, symbol); + const fn = FunctionPrototypeBind(emitHook, undefined, symbol); // Set the name property of the function as it looks good in the stack trace. - Object.defineProperty(fn, 'name', { + ObjectDefineProperty(fn, 'name', { value: name }); return fn; diff --git a/lib/internal/bootstrap/loaders.js b/lib/internal/bootstrap/loaders.js index c8fd613f40df84..b919d628fc1667 100644 --- a/lib/internal/bootstrap/loaders.js +++ b/lib/internal/bootstrap/loaders.js @@ -44,15 +44,17 @@ /* global process, getLinkedBinding, getInternalBinding, primordials */ const { - Reflect, - Object, - ObjectPrototype, - SafeSet + ReflectGet, + ObjectCreate, + ObjectDefineProperty, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + SafeSet, } = primordials; // Set up process.moduleLoadList. const moduleLoadList = []; -Object.defineProperty(process, 'moduleLoadList', { +ObjectDefineProperty(process, 'moduleLoadList', { value: moduleLoadList, configurable: true, enumerable: true, @@ -99,7 +101,7 @@ const internalBindingWhitelist = new SafeSet([ // Set up process.binding() and process._linkedBinding(). { - const bindingObj = Object.create(null); + const bindingObj = ObjectCreate(null); process.binding = function binding(module) { module = String(module); @@ -124,7 +126,7 @@ const internalBindingWhitelist = new SafeSet([ // Set up internalBinding() in the closure. let internalBinding; { - const bindingObj = Object.create(null); + const bindingObj = ObjectCreate(null); // eslint-disable-next-line no-global-assign internalBinding = function internalBinding(module) { let mod = bindingObj[module]; @@ -224,7 +226,7 @@ NativeModule.prototype.compileForPublicLoader = function(needToSyncExports) { // When using --expose-internals, we do not want to reflect the named // exports from core modules as this can trigger unnecessary getters. const internal = this.id.startsWith('internal/'); - this.exportKeys = internal ? [] : Object.keys(this.exports); + this.exportKeys = internal ? [] : ObjectKeys(this.exports); } this.getESMFacade(); this.syncExports(); @@ -233,8 +235,8 @@ NativeModule.prototype.compileForPublicLoader = function(needToSyncExports) { }; const getOwn = (target, property, receiver) => { - return ObjectPrototype.hasOwnProperty(target, property) ? - Reflect.get(target, property, receiver) : + return ObjectPrototypeHasOwnProperty(target, property) ? + ReflectGet(target, property, receiver) : undefined; }; diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js index 18acd9d2b64774..c586ddfd5e6f89 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js @@ -35,7 +35,14 @@ setupPrepareStackTrace(); -const { JSON, Object, Symbol } = primordials; +const { + JSONParse, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectGetPrototypeOf, + ObjectSetPrototypeOf, + SymbolToStringTag, +} = primordials; const config = internalBinding('config'); const { deprecate } = require('internal/util'); @@ -64,7 +71,7 @@ if (ownsProcessState) { } // process.config is serialized config.gypi -process.config = JSON.parse(internalBinding('native_module').config); +process.config = JSONParse(internalBinding('native_module').config); const rawMethods = internalBinding('process_methods'); // Set up methods and events on the process object for the main thread @@ -205,7 +212,7 @@ const { setTraceCategoryStateUpdateHandler } = internalBinding('trace_events'); setTraceCategoryStateUpdateHandler(perThreadSetup.toggleTraceCategoryState); // process.allowedNodeEnvironmentFlags -Object.defineProperty(process, 'allowedNodeEnvironmentFlags', { +ObjectDefineProperty(process, 'allowedNodeEnvironmentFlags', { get() { const flags = perThreadSetup.buildAllowedFlags(); process.allowedNodeEnvironmentFlags = flags; @@ -214,7 +221,7 @@ Object.defineProperty(process, 'allowedNodeEnvironmentFlags', { // If the user tries to set this to another value, override // this completely to that value. set(value) { - Object.defineProperty(this, 'allowedNodeEnvironmentFlags', { + ObjectDefineProperty(this, 'allowedNodeEnvironmentFlags', { value, configurable: true, enumerable: true, @@ -234,7 +241,7 @@ process.assert = deprecate( // TODO(joyeecheung): this property has not been well-maintained, should we // deprecate it in favor of a better API? const { isDebugBuild, hasOpenSSL, hasInspector } = config; -Object.defineProperty(process, 'features', { +ObjectDefineProperty(process, 'features', { enumerable: true, writable: false, configurable: false, @@ -318,17 +325,17 @@ function setupPrepareStackTrace() { function setupProcessObject() { const EventEmitter = require('events'); - const origProcProto = Object.getPrototypeOf(process); - Object.setPrototypeOf(origProcProto, EventEmitter.prototype); + const origProcProto = ObjectGetPrototypeOf(process); + ObjectSetPrototypeOf(origProcProto, EventEmitter.prototype); EventEmitter.call(process); - Object.defineProperty(process, Symbol.toStringTag, { + ObjectDefineProperty(process, SymbolToStringTag, { enumerable: false, writable: true, configurable: false, value: 'process' }); // Make process globally available to users by putting it on the global proxy - Object.defineProperty(global, 'process', { + ObjectDefineProperty(global, 'process', { value: process, enumerable: false, writable: true, @@ -337,19 +344,19 @@ function setupProcessObject() { } function setupProcessStdio(getStdout, getStdin, getStderr) { - Object.defineProperty(process, 'stdout', { + ObjectDefineProperty(process, 'stdout', { configurable: true, enumerable: true, get: getStdout }); - Object.defineProperty(process, 'stderr', { + ObjectDefineProperty(process, 'stderr', { configurable: true, enumerable: true, get: getStderr }); - Object.defineProperty(process, 'stdin', { + ObjectDefineProperty(process, 'stdin', { configurable: true, enumerable: true, get: getStdin @@ -362,7 +369,7 @@ function setupProcessStdio(getStdout, getStdin, getStderr) { } function setupGlobalProxy() { - Object.defineProperty(global, Symbol.toStringTag, { + ObjectDefineProperty(global, SymbolToStringTag, { value: 'global', writable: false, enumerable: false, @@ -377,7 +384,7 @@ function setupGlobalProxy() { function makeSetter(name) { return deprecate(function(value) { - Object.defineProperty(this, name, { + ObjectDefineProperty(this, name, { configurable: true, writable: true, enumerable: true, @@ -386,7 +393,7 @@ function setupGlobalProxy() { }, `'${name}' is deprecated, use 'global'`, 'DEP0016'); } - Object.defineProperties(global, { + ObjectDefineProperties(global, { GLOBAL: { configurable: true, get: makeGetter('GLOBAL'), @@ -409,7 +416,7 @@ function setupBuffer() { delete bufferBinding.setBufferPrototype; delete bufferBinding.zeroFill; - Object.defineProperty(global, 'Buffer', { + ObjectDefineProperty(global, 'Buffer', { value: Buffer, enumerable: false, writable: true, @@ -436,7 +443,7 @@ function createGlobalConsole(consoleFromVM) { // https://heycam.github.io/webidl/#es-namespaces function exposeNamespace(target, name, namespaceObject) { - Object.defineProperty(target, name, { + ObjectDefineProperty(target, name, { writable: true, enumerable: false, configurable: true, @@ -446,7 +453,7 @@ function exposeNamespace(target, name, namespaceObject) { // https://heycam.github.io/webidl/#es-interfaces function exposeInterface(target, name, interfaceObject) { - Object.defineProperty(target, name, { + ObjectDefineProperty(target, name, { writable: true, enumerable: false, configurable: true, @@ -456,7 +463,7 @@ function exposeInterface(target, name, interfaceObject) { // https://heycam.github.io/webidl/#define-the-operations function defineOperation(target, name, method) { - Object.defineProperty(target, name, { + ObjectDefineProperty(target, name, { writable: true, enumerable: true, configurable: true, diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index afd866c9a2b255..1db758f424e2e7 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object, SafeWeakMap } = primordials; +const { + ObjectDefineProperty, + SafeWeakMap, +} = primordials; const { getOptionValue } = require('internal/options'); const { Buffer } = require('buffer'); @@ -71,7 +74,7 @@ function patchProcessObject(expandArgv1) { patchProcessObjectNative(process); - Object.defineProperty(process, 'argv0', { + ObjectDefineProperty(process, 'argv0', { enumerable: true, configurable: false, value: process.argv[0] @@ -104,7 +107,7 @@ function patchProcessObject(expandArgv1) { function addReadOnlyProcessAlias(name, option, enumerable = true) { const value = getOptionValue(option); if (value) { - Object.defineProperty(process, name, { + ObjectDefineProperty(process, name, { writable: false, configurable: true, enumerable, @@ -150,7 +153,7 @@ function initializeReport() { } const { report } = require('internal/process/report'); const { emitExperimentalWarning } = require('internal/util'); - Object.defineProperty(process, 'report', { + ObjectDefineProperty(process, 'report', { enumerable: false, configurable: true, get() { @@ -270,7 +273,7 @@ function initializeDeprecations() { // process.features. const { noBrowserGlobals } = internalBinding('config'); if (noBrowserGlobals) { - Object.defineProperty(process, '_noBrowserGlobals', { + ObjectDefineProperty(process, '_noBrowserGlobals', { writable: false, enumerable: true, configurable: true, @@ -292,7 +295,7 @@ function initializeDeprecations() { // deprecation path for these in ES Modules. // See https://github.com/nodejs/node/pull/26334. let _process = process; - Object.defineProperty(global, 'process', { + ObjectDefineProperty(global, 'process', { get() { return _process; }, @@ -304,7 +307,7 @@ function initializeDeprecations() { }); let _Buffer = Buffer; - Object.defineProperty(global, 'Buffer', { + ObjectDefineProperty(global, 'Buffer', { get() { return _Buffer; }, diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index acd7d319d5e1b2..a14909e491c4f2 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1,6 +1,8 @@ 'use strict'; -const { Math } = primordials; +const { + MathFloor, +} = primordials; const { ERR_BUFFER_OUT_OF_BOUNDS, @@ -61,7 +63,7 @@ function checkInt(value, min, max, buf, offset, byteLength) { } function boundsError(value, length, type) { - if (Math.floor(value) !== value) { + if (MathFloor(value) !== value) { validateNumber(value, type); throw new ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value); } @@ -644,7 +646,7 @@ function writeU_Int48LE(buf, value, offset, min, max) { value = +value; checkInt(value, min, max, buf, offset, 5); - const newVal = Math.floor(value * 2 ** -32); + const newVal = MathFloor(value * 2 ** -32); buf[offset++] = value; value = value >>> 8; buf[offset++] = value; @@ -669,7 +671,7 @@ function writeU_Int40LE(buf, value, offset, min, max) { buf[offset++] = value; value = value >>> 8; buf[offset++] = value; - buf[offset++] = Math.floor(newVal * 2 ** -32); + buf[offset++] = MathFloor(newVal * 2 ** -32); return offset; } @@ -755,7 +757,7 @@ function writeU_Int48BE(buf, value, offset, min, max) { value = +value; checkInt(value, min, max, buf, offset, 5); - const newVal = Math.floor(value * 2 ** -32); + const newVal = MathFloor(value * 2 ** -32); buf[offset++] = (newVal >>> 8); buf[offset++] = newVal; buf[offset + 3] = value; @@ -772,7 +774,7 @@ function writeU_Int40BE(buf, value, offset, min, max) { value = +value; checkInt(value, min, max, buf, offset, 4); - buf[offset++] = Math.floor(value * 2 ** -32); + buf[offset++] = MathFloor(value * 2 ** -32); buf[offset + 3] = value; value = value >>> 8; buf[offset + 2] = value; diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 2abdb58c3c8b89..0f028e2e028fa2 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const { errnoException, @@ -281,8 +284,8 @@ function ChildProcess() { maybeClose(this); }; } -Object.setPrototypeOf(ChildProcess.prototype, EventEmitter.prototype); -Object.setPrototypeOf(ChildProcess, EventEmitter); +ObjectSetPrototypeOf(ChildProcess.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(ChildProcess, EventEmitter); function flushStdio(subprocess) { @@ -526,7 +529,7 @@ function setupChannel(target, channel, serializationMode) { target.channel = channel; // _channel can be deprecated in version 8 - Object.defineProperty(target, '_channel', { + ObjectDefineProperty(target, '_channel', { get() { return target.channel; }, set(val) { target.channel = val; }, enumerable: true diff --git a/lib/internal/child_process/serialization.js b/lib/internal/child_process/serialization.js index 1381f299265e4c..48b6d7ffe00bf6 100644 --- a/lib/internal/child_process/serialization.js +++ b/lib/internal/child_process/serialization.js @@ -1,6 +1,9 @@ 'use strict'; -const { JSON } = primordials; +const { + JSONParse, + JSONStringify, +} = primordials; const { Buffer } = require('buffer'); const { StringDecoder } = require('string_decoder'); const v8 = require('v8'); @@ -104,14 +107,14 @@ const json = { } else { chunks[0] = channel[kJSONBuffer] + chunks[0]; for (let i = 0; i < numCompleteChunks; i++) - yield JSON.parse(chunks[i]); + yield JSONParse(chunks[i]); channel[kJSONBuffer] = incompleteChunk; } channel.buffering = channel[kJSONBuffer].length !== 0; }, writeChannelMessage(channel, req, message, handle) { - const string = JSON.stringify(message) + '\n'; + const string = JSONStringify(message) + '\n'; return channel.writeUtf8String(req, string, handle); }, }; diff --git a/lib/internal/cli_table.js b/lib/internal/cli_table.js index ca8b206fd76394..f0f09b4f8fe870 100644 --- a/lib/internal/cli_table.js +++ b/lib/internal/cli_table.js @@ -1,6 +1,10 @@ 'use strict'; -const { Math, ObjectPrototype } = primordials; +const { + MathCeil, + MathMax, + ObjectPrototypeHasOwnProperty, +} = primordials; const { getStringWidth } = require('internal/readline/utils'); @@ -36,7 +40,7 @@ const renderRow = (row, columnWidths) => { const needed = (columnWidths[i] - len) / 2; // round(needed) + ceil(needed) will always add up to the amount // of spaces we need while also left justifying the output. - out += `${' '.repeat(needed)}${cell}${' '.repeat(Math.ceil(needed))}`; + out += `${' '.repeat(needed)}${cell}${' '.repeat(MathCeil(needed))}`; if (i !== row.length - 1) out += tableChars.middle; } @@ -47,7 +51,7 @@ const renderRow = (row, columnWidths) => { const table = (head, columns) => { const rows = []; const columnWidths = head.map((h) => getStringWidth(h)); - const longestColumn = columns.reduce((n, a) => Math.max(n, a.length), 0); + const longestColumn = columns.reduce((n, a) => MathMax(n, a.length), 0); for (let i = 0; i < head.length; i++) { const column = columns[i]; @@ -55,10 +59,10 @@ const table = (head, columns) => { if (rows[j] === undefined) rows[j] = []; const value = rows[j][i] = - ObjectPrototype.hasOwnProperty(column, j) ? column[j] : ''; + ObjectPrototypeHasOwnProperty(column, j) ? column[j] : ''; const width = columnWidths[i] || 0; const counted = getStringWidth(value); - columnWidths[i] = Math.max(width, counted); + columnWidths[i] = MathMax(width, counted); } } diff --git a/lib/internal/cluster/child.js b/lib/internal/cluster/child.js index 5f28d2804724d8..ed5d7ce76dbc90 100644 --- a/lib/internal/cluster/child.js +++ b/lib/internal/cluster/child.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, +} = primordials; const assert = require('internal/assert'); const path = require('path'); @@ -154,7 +156,7 @@ function rr(message, indexesKey, cb) { function getsockname(out) { if (key) - Object.assign(out, message.sockname); + ObjectAssign(out, message.sockname); return 0; } diff --git a/lib/internal/cluster/master.js b/lib/internal/cluster/master.js index 645d8f1bd89931..bee224a67d9406 100644 --- a/lib/internal/cluster/master.js +++ b/lib/internal/cluster/master.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectKeys, + ObjectValues, +} = primordials; const assert = require('internal/assert'); const { fork } = require('child_process'); @@ -82,7 +85,7 @@ cluster.setupMaster = function(options) { if (message.cmd !== 'NODE_DEBUG_ENABLED') return; - for (const worker of Object.values(cluster.workers)) { + for (const worker of ObjectValues(cluster.workers)) { if (worker.state === 'online' || worker.state === 'listening') { process._debugProcess(worker.process.pid); } else { @@ -144,7 +147,7 @@ function removeWorker(worker) { assert(worker); delete cluster.workers[worker.id]; - if (Object.keys(cluster.workers).length === 0) { + if (ObjectKeys(cluster.workers).length === 0) { assert(handles.size === 0, 'Resource leak detected.'); intercom.emit('disconnect'); } @@ -222,12 +225,12 @@ function emitForkNT(worker) { } cluster.disconnect = function(cb) { - const workers = Object.keys(cluster.workers); + const workers = ObjectKeys(cluster.workers); if (workers.length === 0) { process.nextTick(() => intercom.emit('disconnect')); } else { - for (const worker of Object.values(cluster.workers)) { + for (const worker of ObjectValues(cluster.workers)) { if (worker.isConnected()) { worker.disconnect(); } diff --git a/lib/internal/cluster/worker.js b/lib/internal/cluster/worker.js index 4563b2e663b686..516b7a3b73d787 100644 --- a/lib/internal/cluster/worker.js +++ b/lib/internal/cluster/worker.js @@ -1,9 +1,7 @@ 'use strict'; const { - Object: { - setPrototypeOf: ObjectSetPrototypeOf - } + ObjectSetPrototypeOf, } = primordials; const EventEmitter = require('events'); diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index f79b703e592aed..4df71eb31dbeaa 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -3,7 +3,14 @@ // The Console constructor is not actually used to construct the global // console. It's exported for backwards compatibility. -const { Object, ObjectPrototype, Reflect } = primordials; +const { + ObjectDefineProperties, + ObjectDefineProperty, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ObjectValues, + ReflectOwnKeys, +} = primordials; const { trace } = internalBinding('trace_events'); const { @@ -102,7 +109,7 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) { } // Bind the prototype functions to this Console instance - const keys = Object.keys(Console.prototype); + const keys = ObjectKeys(Console.prototype); for (var v = 0; v < keys.length; v++) { var k = keys[v]; // We have to bind the methods grabbed from the instance instead of from @@ -122,7 +129,7 @@ const consolePropAttributes = { }; // Fixup global.console instanceof global.console.Console -Object.defineProperty(Console, Symbol.hasInstance, { +ObjectDefineProperty(Console, Symbol.hasInstance, { value(instance) { return instance[kIsConsole]; } @@ -130,7 +137,7 @@ Object.defineProperty(Console, Symbol.hasInstance, { // Eager version for the Console constructor Console.prototype[kBindStreamsEager] = function(stdout, stderr) { - Object.defineProperties(this, { + ObjectDefineProperties(this, { '_stdout': { ...consolePropAttributes, value: stdout }, '_stderr': { ...consolePropAttributes, value: stderr } }); @@ -141,7 +148,7 @@ Console.prototype[kBindStreamsEager] = function(stdout, stderr) { Console.prototype[kBindStreamsLazy] = function(object) { let stdout; let stderr; - Object.defineProperties(this, { + ObjectDefineProperties(this, { '_stdout': { enumerable: false, configurable: true, @@ -164,7 +171,7 @@ Console.prototype[kBindStreamsLazy] = function(object) { }; Console.prototype[kBindProperties] = function(ignoreErrors, colorMode) { - Object.defineProperties(this, { + ObjectDefineProperties(this, { '_stdoutErrorHandler': { ...consolePropAttributes, value: createWriteErrorHandler(this, kUseStdout) @@ -408,7 +415,7 @@ const consoleMethods = { const depth = v !== null && typeof v === 'object' && !isArray(v) && - Object.keys(v).length > 2 ? -1 : 0; + ObjectKeys(v).length > 2 ? -1 : 0; const opt = { depth, maxArrayLength: 3, @@ -473,7 +480,7 @@ const consoleMethods = { const map = {}; let hasPrimitives = false; const valuesKeyArray = []; - const indexKeyArray = Object.keys(tabularData); + const indexKeyArray = ObjectKeys(tabularData); for (; i < indexKeyArray.length; i++) { const item = tabularData[indexKeyArray[i]]; @@ -483,12 +490,12 @@ const consoleMethods = { hasPrimitives = true; valuesKeyArray[i] = _inspect(item); } else { - const keys = properties || Object.keys(item); + const keys = properties || ObjectKeys(item); for (const key of keys) { if (map[key] === undefined) map[key] = []; if ((primitive && properties) || - !ObjectPrototype.hasOwnProperty(item, key)) + !ObjectPrototypeHasOwnProperty(item, key)) map[key][i] = ''; else map[key][i] = _inspect(item[key]); @@ -496,8 +503,8 @@ const consoleMethods = { } } - const keys = Object.keys(map); - const values = Object.values(map); + const keys = ObjectKeys(map); + const values = ObjectValues(map); if (hasPrimitives) { keys.push(valuesKey); values.push(valuesKeyArray); @@ -535,7 +542,7 @@ const isArray = (v) => ArrayIsArray(v) || isTypedArray(v) || isBuffer(v); function noop() {} -for (const method of Reflect.ownKeys(consoleMethods)) +for (const method of ReflectOwnKeys(consoleMethods)) Console.prototype[method] = consoleMethods[method]; Console.prototype.debug = Console.prototype.log; diff --git a/lib/internal/console/global.js b/lib/internal/console/global.js index bad7478f1e1131..6a1dc3806fdb0b 100644 --- a/lib/internal/console/global.js +++ b/lib/internal/console/global.js @@ -12,7 +12,12 @@ // Therefore, the console.Console.prototype is not // in the global console prototype chain anymore. -const { Object, Reflect } = primordials; +const { + ObjectCreate, + ReflectDefineProperty, + ReflectGetOwnPropertyDescriptor, + ReflectOwnKeys, +} = primordials; const { Console, @@ -20,20 +25,20 @@ const { kBindProperties } = require('internal/console/constructor'); -const globalConsole = Object.create({}); +const globalConsole = ObjectCreate({}); // Since Console is not on the prototype chain of the global console, // the symbol properties on Console.prototype have to be looked up from // the global console itself. In addition, we need to make the global // console a namespace by binding the console methods directly onto // the global console with the receiver fixed. -for (const prop of Reflect.ownKeys(Console.prototype)) { +for (const prop of ReflectOwnKeys(Console.prototype)) { if (prop === 'constructor') { continue; } - const desc = Reflect.getOwnPropertyDescriptor(Console.prototype, prop); + const desc = ReflectGetOwnPropertyDescriptor(Console.prototype, prop); if (typeof desc.value === 'function') { // fix the receiver desc.value = desc.value.bind(globalConsole); } - Reflect.defineProperty(globalConsole, prop, desc); + ReflectDefineProperty(globalConsole, prop, desc); } globalConsole[kBindStreamsLazy](process); diff --git a/lib/internal/crypto/cipher.js b/lib/internal/crypto/cipher.js index 1d6f32bf7b809a..ee1422da0fd2d5 100644 --- a/lib/internal/crypto/cipher.js +++ b/lib/internal/crypto/cipher.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const { RSA_PKCS1_OAEP_PADDING, @@ -126,8 +128,8 @@ function Cipher(cipher, password, options) { createCipher.call(this, cipher, password, options, true); } -Object.setPrototypeOf(Cipher.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Cipher, LazyTransform); +ObjectSetPrototypeOf(Cipher.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Cipher, LazyTransform); Cipher.prototype._transform = function _transform(chunk, encoding, callback) { this.push(this[kHandle].update(chunk, encoding)); @@ -237,8 +239,8 @@ function addCipherPrototypeFunctions(constructor) { constructor.prototype.setAAD = Cipher.prototype.setAAD; } -Object.setPrototypeOf(Cipheriv.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Cipheriv, LazyTransform); +ObjectSetPrototypeOf(Cipheriv.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Cipheriv, LazyTransform); addCipherPrototypeFunctions(Cipheriv); function Decipher(cipher, password, options) { @@ -248,8 +250,8 @@ function Decipher(cipher, password, options) { createCipher.call(this, cipher, password, options, false); } -Object.setPrototypeOf(Decipher.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Decipher, LazyTransform); +ObjectSetPrototypeOf(Decipher.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Decipher, LazyTransform); addCipherPrototypeFunctions(Decipher); @@ -260,8 +262,8 @@ function Decipheriv(cipher, key, iv, options) { createCipherWithIV.call(this, cipher, key, options, false, iv); } -Object.setPrototypeOf(Decipheriv.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Decipheriv, LazyTransform); +ObjectSetPrototypeOf(Decipheriv.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Decipheriv, LazyTransform); addCipherPrototypeFunctions(Decipheriv); module.exports = { diff --git a/lib/internal/crypto/diffiehellman.js b/lib/internal/crypto/diffiehellman.js index 7e0fde38bcbe10..da8f87bf16d4f6 100644 --- a/lib/internal/crypto/diffiehellman.js +++ b/lib/internal/crypto/diffiehellman.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const { Buffer } = require('buffer'); const { @@ -63,7 +65,7 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { generator = toBuf(generator, genEncoding); this[kHandle] = new _DiffieHellman(sizeOrKey, generator); - Object.defineProperty(this, 'verifyError', { + ObjectDefineProperty(this, 'verifyError', { enumerable: true, value: this[kHandle].verifyError, writable: false @@ -75,7 +77,7 @@ function DiffieHellmanGroup(name) { if (!(this instanceof DiffieHellmanGroup)) return new DiffieHellmanGroup(name); this[kHandle] = new _DiffieHellmanGroup(name); - Object.defineProperty(this, 'verifyError', { + ObjectDefineProperty(this, 'verifyError', { enumerable: true, value: this[kHandle].verifyError, writable: false diff --git a/lib/internal/crypto/hash.js b/lib/internal/crypto/hash.js index 4816e36d458107..526afed48c0834 100644 --- a/lib/internal/crypto/hash.js +++ b/lib/internal/crypto/hash.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const { Hash: _Hash, @@ -49,8 +51,8 @@ function Hash(algorithm, options) { LazyTransform.call(this, options); } -Object.setPrototypeOf(Hash.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Hash, LazyTransform); +ObjectSetPrototypeOf(Hash.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Hash, LazyTransform); Hash.prototype.copy = function copy(options) { const state = this[kState]; @@ -116,8 +118,8 @@ function Hmac(hmac, key, options) { LazyTransform.call(this, options); } -Object.setPrototypeOf(Hmac.prototype, LazyTransform.prototype); -Object.setPrototypeOf(Hmac, LazyTransform); +ObjectSetPrototypeOf(Hmac.prototype, LazyTransform.prototype); +ObjectSetPrototypeOf(Hmac, LazyTransform); Hmac.prototype.update = Hash.prototype.update; diff --git a/lib/internal/crypto/keygen.js b/lib/internal/crypto/keygen.js index 0a4bde77fa369b..88d2822fa6fad0 100644 --- a/lib/internal/crypto/keygen.js +++ b/lib/internal/crypto/keygen.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const { AsyncWrap, Providers } = internalBinding('async_wrap'); const { @@ -63,7 +65,7 @@ function generateKeyPair(type, options, callback) { handleError(impl(wrap)); } -Object.defineProperty(generateKeyPair, customPromisifyArgs, { +ObjectDefineProperty(generateKeyPair, customPromisifyArgs, { value: ['publicKey', 'privateKey'], enumerable: false }); diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index 250147d7529439..25ef8884953bc9 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const { KeyObject: KeyObjectHandle, @@ -48,7 +50,7 @@ class KeyObject { this[kKeyType] = type; - Object.defineProperty(this, kHandle, { + ObjectDefineProperty(this, kHandle, { value: handle, enumerable: false, configurable: false, diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index f42458aa788985..425b65e2684d4e 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -1,6 +1,8 @@ 'use strict'; -const { Math } = primordials; +const { + MathMin, +} = primordials; const { AsyncWrap, Providers } = internalBinding('async_wrap'); const { Buffer, kMaxLength } = require('buffer'); @@ -14,13 +16,13 @@ const { validateNumber } = require('internal/validators'); const { isArrayBufferView } = require('internal/util/types'); const kMaxUint32 = 2 ** 32 - 1; -const kMaxPossibleLength = Math.min(kMaxLength, kMaxUint32); +const kMaxPossibleLength = MathMin(kMaxLength, kMaxUint32); function assertOffset(offset, elementSize, length) { validateNumber(offset, 'offset'); offset *= elementSize; - const maxLength = Math.min(length, kMaxPossibleLength); + const maxLength = MathMin(length, kMaxPossibleLength); if (Number.isNaN(offset) || offset > maxLength || offset < 0) { throw new ERR_OUT_OF_RANGE('offset', `>= 0 && <= ${maxLength}`, offset); } diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index 6eda8455643848..27930ce1acf793 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const { ERR_CRYPTO_SIGN_KEY_REQUIRED, @@ -38,8 +40,8 @@ function Sign(algorithm, options) { Writable.call(this, options); } -Object.setPrototypeOf(Sign.prototype, Writable.prototype); -Object.setPrototypeOf(Sign, Writable); +ObjectSetPrototypeOf(Sign.prototype, Writable.prototype); +ObjectSetPrototypeOf(Sign, Writable); Sign.prototype._write = function _write(chunk, encoding, callback) { this.update(chunk, encoding); @@ -153,8 +155,8 @@ function Verify(algorithm, options) { Writable.call(this, options); } -Object.setPrototypeOf(Verify.prototype, Writable.prototype); -Object.setPrototypeOf(Verify, Writable); +ObjectSetPrototypeOf(Verify.prototype, Writable.prototype); +ObjectSetPrototypeOf(Verify, Writable); Verify.prototype._write = Sign.prototype._write; Verify.prototype.update = Sign.prototype.update; diff --git a/lib/internal/dns/promises.js b/lib/internal/dns/promises.js index 306d5eee477343..c4bbc21ae5528c 100644 --- a/lib/internal/dns/promises.js +++ b/lib/internal/dns/promises.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, + ObjectDefineProperty, +} = primordials; const { bindDefaultResolver, @@ -203,12 +206,12 @@ function resolver(bindingName) { return createResolverPromise(this, bindingName, name, ttl); } - Object.defineProperty(query, 'name', { value: bindingName }); + ObjectDefineProperty(query, 'name', { value: bindingName }); return query; } -const resolveMap = Object.create(null); +const resolveMap = ObjectCreate(null); // Resolver instances correspond 1:1 to c-ares channels. class Resolver { diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index 6aacfcd45a3afd..fe940f6e860497 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -3,7 +3,11 @@ // An implementation of the WHATWG Encoding Standard // https://encoding.spec.whatwg.org -const { Object } = primordials; +const { + ObjectCreate, + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptors, +} = primordials; const { ERR_ENCODING_INVALID_ENCODED_DATA, @@ -339,7 +343,7 @@ class TextEncoder { if (typeof depth === 'number' && depth < 0) return this; const ctor = getConstructorOf(this); - const obj = Object.create({ + const obj = ObjectCreate({ constructor: ctor === null ? TextEncoder : ctor }); obj.encoding = this.encoding; @@ -348,7 +352,7 @@ class TextEncoder { } } -Object.defineProperties( +ObjectDefineProperties( TextEncoder.prototype, { 'encode': { enumerable: true }, 'encodeInto': { enumerable: true }, @@ -508,9 +512,9 @@ function makeTextDecoderJS() { // Mix in some shared properties. { - Object.defineProperties( + ObjectDefineProperties( TextDecoder.prototype, - Object.getOwnPropertyDescriptors({ + ObjectGetOwnPropertyDescriptors({ get encoding() { validateDecoder(this); return this[kEncoding]; @@ -532,7 +536,7 @@ function makeTextDecoderJS() { if (typeof depth === 'number' && depth < 0) return this; const ctor = getConstructorOf(this); - const obj = Object.create({ + const obj = ObjectCreate({ constructor: ctor === null ? TextDecoder : ctor }); obj.encoding = this.encoding; @@ -546,7 +550,7 @@ function makeTextDecoderJS() { return require('internal/util/inspect').inspect(obj, opts); } })); - Object.defineProperties(TextDecoder.prototype, { + ObjectDefineProperties(TextDecoder.prototype, { decode: { enumerable: true }, [inspect]: { enumerable: false }, [Symbol.toStringTag]: { diff --git a/lib/internal/error-serdes.js b/lib/internal/error-serdes.js index 4a07e92d769cf3..1216c56bffe5c2 100644 --- a/lib/internal/error-serdes.js +++ b/lib/internal/error-serdes.js @@ -2,10 +2,16 @@ const Buffer = require('buffer').Buffer; const { - ArrayPrototype, - FunctionPrototype, - Object, - ObjectPrototype, + ArrayPrototypeForEach, + FunctionPrototypeCall, + ObjectAssign, + ObjectCreate, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptor, + ObjectGetOwnPropertyNames, + ObjectGetPrototypeOf, + ObjectKeys, + ObjectPrototypeToString, SafeSet, } = primordials; @@ -16,24 +22,24 @@ const kInspectedError = 2; const errors = { Error, TypeError, RangeError, URIError, SyntaxError, ReferenceError, EvalError }; -const errorConstructorNames = new SafeSet(Object.keys(errors)); +const errorConstructorNames = new SafeSet(ObjectKeys(errors)); function TryGetAllProperties(object, target = object) { - const all = Object.create(null); + const all = ObjectCreate(null); if (object === null) return all; - Object.assign(all, - TryGetAllProperties(Object.getPrototypeOf(object), target)); - const keys = Object.getOwnPropertyNames(object); - ArrayPrototype.forEach(keys, (key) => { + ObjectAssign(all, + TryGetAllProperties(ObjectGetPrototypeOf(object), target)); + const keys = ObjectGetOwnPropertyNames(object); + ArrayPrototypeForEach(keys, (key) => { let descriptor; try { - descriptor = Object.getOwnPropertyDescriptor(object, key); + descriptor = ObjectGetOwnPropertyDescriptor(object, key); } catch { return; } const getter = descriptor.get; if (getter && key !== '__proto__') { try { - descriptor.value = FunctionPrototype.call(getter, target); + descriptor.value = FunctionPrototypeCall(getter, target); } catch {} } if ('value' in descriptor && typeof descriptor.value !== 'function') { @@ -50,10 +56,10 @@ function GetConstructors(object) { for (let current = object; current !== null; - current = Object.getPrototypeOf(current)) { - const desc = Object.getOwnPropertyDescriptor(current, 'constructor'); + current = ObjectGetPrototypeOf(current)) { + const desc = ObjectGetOwnPropertyDescriptor(current, 'constructor'); if (desc && desc.value) { - Object.defineProperty(constructors, constructors.length, { + ObjectDefineProperty(constructors, constructors.length, { value: desc.value, enumerable: true }); } @@ -63,7 +69,7 @@ function GetConstructors(object) { } function GetName(object) { - const desc = Object.getOwnPropertyDescriptor(object, 'name'); + const desc = ObjectGetOwnPropertyDescriptor(object, 'name'); return desc && desc.value; } @@ -80,7 +86,7 @@ function serializeError(error) { if (!serialize) serialize = require('v8').serialize; try { if (typeof error === 'object' && - ObjectPrototype.toString(error) === '[object Error]') { + ObjectPrototypeToString(error) === '[object Error]') { const constructors = GetConstructors(error); for (let i = 0; i < constructors.length; i++) { const name = GetName(constructors[i]); @@ -109,7 +115,7 @@ function deserializeError(error) { case kSerializedError: const { constructor, properties } = deserialize(error.subarray(1)); const ctor = errors[constructor]; - return Object.create(ctor.prototype, properties); + return ObjectCreate(ctor.prototype, properties); case kSerializedObject: return deserialize(error.subarray(1)); case kInspectedError: diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 2e851867c74a51..b6f1067d57f21c 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -10,7 +10,11 @@ // value statically and permanently identifies the error. While the error // message may change, the code should not. -const { Object, Math } = primordials; +const { + MathAbs, + ObjectDefineProperty, + ObjectKeys, +} = primordials; const messages = new Map(); const codes = {}; @@ -121,7 +125,7 @@ class SystemError extends Error { if (context.dest !== undefined) message += ` => ${context.dest}`; - Object.defineProperty(this, 'message', { + ObjectDefineProperty(this, 'message', { value: message, enumerable: false, writable: true, @@ -131,14 +135,14 @@ class SystemError extends Error { this.code = key; - Object.defineProperty(this, 'info', { + ObjectDefineProperty(this, 'info', { value: context, enumerable: true, configurable: true, writable: false }); - Object.defineProperty(this, 'errno', { + ObjectDefineProperty(this, 'errno', { get() { return context.errno; }, @@ -149,7 +153,7 @@ class SystemError extends Error { configurable: true }); - Object.defineProperty(this, 'syscall', { + ObjectDefineProperty(this, 'syscall', { get() { return context.syscall; }, @@ -166,7 +170,7 @@ class SystemError extends Error { // always be of type string. We should probably just remove the // `.toString()` and `Buffer.from()` operations and set the value on the // context as the user did. - Object.defineProperty(this, 'path', { + ObjectDefineProperty(this, 'path', { get() { return context.path != null ? context.path.toString() : context.path; @@ -181,7 +185,7 @@ class SystemError extends Error { } if (context.dest !== undefined) { - Object.defineProperty(this, 'dest', { + ObjectDefineProperty(this, 'dest', { get() { return context.dest != null ? context.dest.toString() : context.dest; @@ -230,7 +234,7 @@ function makeNodeErrorWithCode(Base, key) { Error.stackTraceLimit = limit; } const message = getMessage(key, args, this); - Object.defineProperty(this, 'message', { + ObjectDefineProperty(this, 'message', { value: message, enumerable: false, writable: true, @@ -278,7 +282,7 @@ function addCodeToName(err, name, code) { err.stack; // Reset the name to the actual name. if (name === 'SystemError') { - Object.defineProperty(err, 'name', { + ObjectDefineProperty(err, 'name', { value: name, enumerable: false, writable: true, @@ -391,7 +395,7 @@ function uvException(ctx) { const err = new Error(message); Error.stackTraceLimit = tmpLimit; - for (const prop of Object.keys(ctx)) { + for (const prop of ObjectKeys(ctx)) { if (prop === 'message' || prop === 'path' || prop === 'dest') { continue; } @@ -1108,7 +1112,7 @@ E('ERR_OUT_OF_RANGE', let msg = replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`; let received; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + if (Number.isInteger(input) && MathAbs(input) > 2 ** 32) { received = addNumericalSeparator(String(input)); } else if (typeof input === 'bigint') { received = String(input); diff --git a/lib/internal/freelist.js b/lib/internal/freelist.js index 16437b2b8a7a6d..3e93e04f8dae38 100644 --- a/lib/internal/freelist.js +++ b/lib/internal/freelist.js @@ -1,6 +1,8 @@ 'use strict'; -const { Reflect } = primordials; +const { + ReflectApply, +} = primordials; class FreeList { constructor(name, max, ctor) { @@ -17,7 +19,7 @@ class FreeList { alloc() { return this.list.length > 0 ? this.list.pop() : - Reflect.apply(this.ctor, this, arguments); + ReflectApply(this.ctor, this, arguments); } free(obj) { diff --git a/lib/internal/fs/dir.js b/lib/internal/fs/dir.js index 90ab31fe5abc73..c4e0a3746c125a 100644 --- a/lib/internal/fs/dir.js +++ b/lib/internal/fs/dir.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const pathModule = require('path'); const binding = internalBinding('fs'); @@ -172,7 +174,7 @@ class Dir { } } -Object.defineProperty(Dir.prototype, Symbol.asyncIterator, { +ObjectDefineProperty(Dir.prototype, Symbol.asyncIterator, { value: Dir.prototype.entries, enumerable: false, writable: true, diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index c58c0698d30cf0..b078091acb1b3f 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1,6 +1,9 @@ 'use strict'; -const { Math } = primordials; +const { + MathMax, + MathMin, +} = primordials; const { F_OK, @@ -134,7 +137,7 @@ async function writeFileHandle(filehandle, data, options) { do { const { bytesWritten } = await write(filehandle, buffer, 0, - Math.min(16384, buffer.length)); + MathMin(16384, buffer.length)); remaining -= bytesWritten; buffer = buffer.slice(bytesWritten); } while (remaining > 0); @@ -160,7 +163,7 @@ async function readFileHandle(filehandle, options) { const chunks = []; const chunkSize = size === 0 ? kReadFileMaxChunkSize : - Math.min(size, kReadFileMaxChunkSize); + MathMin(size, kReadFileMaxChunkSize); let endOfFile = false; do { const buf = Buffer.alloc(chunkSize); @@ -290,7 +293,7 @@ async function truncate(path, len = 0) { async function ftruncate(handle, len = 0) { validateFileHandle(handle); validateInteger(len, 'len'); - len = Math.max(0, len); + len = MathMax(0, len); return binding.ftruncate(handle.fd, len, kUsePromises); } diff --git a/lib/internal/fs/read_file_context.js b/lib/internal/fs/read_file_context.js index e1de8fc7cda2c3..d7b0e368006f05 100644 --- a/lib/internal/fs/read_file_context.js +++ b/lib/internal/fs/read_file_context.js @@ -1,6 +1,8 @@ 'use strict'; -const { Math } = primordials; +const { + MathMin, +} = primordials; const { Buffer } = require('buffer'); @@ -87,7 +89,7 @@ class ReadFileContext { } else { buffer = this.buffer; offset = this.pos; - length = Math.min(kReadFileBufferLength, this.size - this.pos); + length = MathMin(kReadFileBufferLength, this.size - this.pos); } const req = new FSReqCallback(); diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index 4d2fc757018156..df2fb4aab4a124 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -1,6 +1,10 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathMin, + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const { ERR_OUT_OF_RANGE @@ -108,8 +112,8 @@ function ReadStream(path, options) { } }); } -Object.setPrototypeOf(ReadStream.prototype, Readable.prototype); -Object.setPrototypeOf(ReadStream, Readable); +ObjectSetPrototypeOf(ReadStream.prototype, Readable.prototype); +ObjectSetPrototypeOf(ReadStream, Readable); ReadStream.prototype.open = function() { fs.open(this.path, this.flags, this.mode, (er, fd) => { @@ -145,13 +149,13 @@ ReadStream.prototype._read = function(n) { // in the thread pool another read() finishes up the pool, and // allocates a new one. const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); + let toRead = MathMin(pool.length - pool.used, n); const start = pool.used; if (this.pos !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); + toRead = MathMin(this.end - this.pos + 1, toRead); else - toRead = Math.min(this.end - this.bytesRead + 1, toRead); + toRead = MathMin(this.end - this.bytesRead + 1, toRead); // Already read everything we were supposed to read! // treat as EOF. @@ -223,7 +227,7 @@ ReadStream.prototype.close = function(cb) { this.destroy(null, cb); }; -Object.defineProperty(ReadStream.prototype, 'pending', { +ObjectDefineProperty(ReadStream.prototype, 'pending', { get() { return this.fd === null; }, configurable: true }); @@ -268,8 +272,8 @@ function WriteStream(path, options) { if (typeof this.fd !== 'number') this.open(); } -Object.setPrototypeOf(WriteStream.prototype, Writable.prototype); -Object.setPrototypeOf(WriteStream, Writable); +ObjectSetPrototypeOf(WriteStream.prototype, Writable.prototype); +ObjectSetPrototypeOf(WriteStream, Writable); WriteStream.prototype._final = function(callback) { if (typeof this.fd !== 'number') { @@ -383,7 +387,7 @@ WriteStream.prototype.close = function(cb) { // There is no shutdown() for files. WriteStream.prototype.destroySoon = WriteStream.prototype.end; -Object.defineProperty(WriteStream.prototype, 'pending', { +ObjectDefineProperty(WriteStream.prototype, 'pending', { get() { return this.fd === null; }, configurable: true }); diff --git a/lib/internal/fs/sync_write_stream.js b/lib/internal/fs/sync_write_stream.js index 522bfc829df303..7d1209ba2decb4 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const { Writable } = require('stream'); const { closeSync, writeSync } = require('fs'); @@ -15,8 +17,8 @@ function SyncWriteStream(fd, options) { this.autoClose = options.autoClose === undefined ? true : options.autoClose; } -Object.setPrototypeOf(SyncWriteStream.prototype, Writable.prototype); -Object.setPrototypeOf(SyncWriteStream, Writable); +ObjectSetPrototypeOf(SyncWriteStream.prototype, Writable.prototype); +ObjectSetPrototypeOf(SyncWriteStream, Writable); SyncWriteStream.prototype._write = function(chunk, encoding, cb) { writeSync(this.fd, chunk, 0, chunk.length); diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index 1a5df71028c942..54569deb8332cf 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object, Reflect } = primordials; +const { + ObjectSetPrototypeOf, + ReflectOwnKeys, +} = primordials; const { Buffer, kMaxLength } = require('buffer'); const { @@ -118,7 +121,7 @@ class DirentFromStats extends Dirent { } } -for (const name of Reflect.ownKeys(Dirent.prototype)) { +for (const name of ReflectOwnKeys(Dirent.prototype)) { if (name === 'constructor') { continue; } @@ -353,8 +356,8 @@ function BigIntStats(dev, mode, nlink, uid, gid, rdev, blksize, this.birthtime = dateFromMs(this.birthtimeMs); } -Object.setPrototypeOf(BigIntStats.prototype, StatsBase.prototype); -Object.setPrototypeOf(BigIntStats, StatsBase); +ObjectSetPrototypeOf(BigIntStats.prototype, StatsBase.prototype); +ObjectSetPrototypeOf(BigIntStats, StatsBase); BigIntStats.prototype._checkModeProperty = function(property) { if (isWindows && (property === S_IFIFO || property === S_IFBLK || @@ -379,8 +382,8 @@ function Stats(dev, mode, nlink, uid, gid, rdev, blksize, this.birthtime = dateFromMs(birthtimeMs); } -Object.setPrototypeOf(Stats.prototype, StatsBase.prototype); -Object.setPrototypeOf(Stats, StatsBase); +ObjectSetPrototypeOf(Stats.prototype, StatsBase.prototype); +ObjectSetPrototypeOf(Stats, StatsBase); // HACK: Workaround for https://github.com/standard-things/esm/issues/821. // TODO(ronag): Remove this as soon as `esm` publishes a fixed version. diff --git a/lib/internal/fs/watchers.js b/lib/internal/fs/watchers.js index bde07cfdc59d41..f04b1c6edeed7e 100644 --- a/lib/internal/fs/watchers.js +++ b/lib/internal/fs/watchers.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const errors = require('internal/errors'); const { @@ -36,8 +39,8 @@ function StatWatcher(bigint) { this[kOldStatus] = -1; this[kUseBigint] = bigint; } -Object.setPrototypeOf(StatWatcher.prototype, EventEmitter.prototype); -Object.setPrototypeOf(StatWatcher, EventEmitter); +ObjectSetPrototypeOf(StatWatcher.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(StatWatcher, EventEmitter); function onchange(newStatus, stats) { const self = this[owner_symbol]; @@ -132,8 +135,8 @@ function FSWatcher() { } }; } -Object.setPrototypeOf(FSWatcher.prototype, EventEmitter.prototype); -Object.setPrototypeOf(FSWatcher, EventEmitter); +ObjectSetPrototypeOf(FSWatcher.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(FSWatcher, EventEmitter); // FIXME(joyeecheung): this method is not documented. @@ -195,7 +198,7 @@ function emitCloseNT(self) { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. -Object.defineProperty(FSEvent.prototype, 'owner', { +ObjectDefineProperty(FSEvent.prototype, 'owner', { get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 86d60ce6435a53..edd3d64ccf0092 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -1,6 +1,12 @@ 'use strict'; -const { Object, ObjectPrototype, Reflect } = primordials; +const { + ObjectAssign, + ObjectCreate, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ReflectGetPrototypeOf, +} = primordials; const assert = require('internal/assert'); const Stream = require('stream'); @@ -120,7 +126,7 @@ function onStreamData(chunk) { function onStreamTrailers(trailers, flags, rawTrailers) { const request = this[kRequest]; if (request !== undefined) { - Object.assign(request[kTrailers], trailers); + ObjectAssign(request[kTrailers], trailers); request[kRawTrailers].push(...rawTrailers); } } @@ -206,8 +212,8 @@ const proxySocketHandler = { }, getPrototypeOf(stream) { if (stream.session !== undefined) - return Reflect.getPrototypeOf(stream.session[kSocket]); - return Reflect.getPrototypeOf(stream); + return ReflectGetPrototypeOf(stream.session[kSocket]); + return ReflectGetPrototypeOf(stream); }, set(stream, prop, value) { switch (prop) { @@ -434,8 +440,8 @@ class Http2ServerResponse extends Stream { sendDate: true, statusCode: HTTP_STATUS_OK, }; - this[kHeaders] = Object.create(null); - this[kTrailers] = Object.create(null); + this[kHeaders] = ObjectCreate(null); + this[kTrailers] = ObjectCreate(null); this[kStream] = stream; stream[kProxySocket] = null; stream[kResponse] = this; @@ -524,7 +530,7 @@ class Http2ServerResponse extends Stream { } addTrailers(headers) { - const keys = Object.keys(headers); + const keys = ObjectKeys(headers); let key = ''; for (let i = 0; i < keys.length; i++) { key = keys[i]; @@ -539,7 +545,7 @@ class Http2ServerResponse extends Stream { } getHeaderNames() { - return Object.keys(this[kHeaders]); + return ObjectKeys(this[kHeaders]); } getHeaders() { @@ -549,7 +555,7 @@ class Http2ServerResponse extends Stream { hasHeader(name) { validateString(name, 'name'); name = name.trim().toLowerCase(); - return ObjectPrototype.hasOwnProperty(this[kHeaders], name); + return ObjectPrototypeHasOwnProperty(this[kHeaders], name); } removeHeader(name) { @@ -617,7 +623,7 @@ class Http2ServerResponse extends Stream { this[kSetHeader](header[0], header[1]); } } else if (typeof headers === 'object') { - const keys = Object.keys(headers); + const keys = ObjectKeys(headers); let key = ''; for (i = 0; i < keys.length; i++) { key = keys[i]; diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 6dc4ba953e52c4..d2ee2538d05921 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -2,7 +2,14 @@ /* eslint-disable no-use-before-define */ -const { Math, Object, Reflect } = primordials; +const { + MathMin, + ObjectAssign, + ObjectCreate, + ObjectDefineProperty, + ObjectPrototypeHasOwnProperty, + ReflectGetPrototypeOf, +} = primordials; const { assertCrypto, @@ -128,8 +135,6 @@ const { kTimeout } = require('internal/timers'); const { isArrayBufferView } = require('internal/util/types'); const { format } = require('internal/util/inspect'); -const hasOwnProperty = Object.prototype.hasOwnProperty; - const { FileHandle } = internalBinding('fs'); const binding = internalBinding('http2'); const { @@ -841,7 +846,7 @@ const proxySocketHandler = { const socket = session[kSocket]; if (socket === undefined) throw new ERR_HTTP2_SOCKET_UNBOUND(); - return Reflect.getPrototypeOf(socket); + return ReflectGetPrototypeOf(socket); }, set(session, prop, value) { switch (prop) { @@ -1585,7 +1590,7 @@ class ClientHttp2Session extends Http2Session { assertIsObject(headers, 'headers'); assertIsObject(options, 'options'); - headers = Object.assign(Object.create(null), headers); + headers = ObjectAssign(ObjectCreate(null), headers); options = { ...options }; if (headers[HTTP2_HEADER_METHOD] === undefined) @@ -2032,7 +2037,7 @@ class Http2Stream extends Duplex { throw new ERR_HTTP2_TRAILERS_NOT_READY(); assertIsObject(headers, 'headers'); - headers = Object.assign(Object.create(null), headers); + headers = ObjectAssign(ObjectCreate(null), headers); debugStreamObj(this, 'sending trailers'); @@ -2167,13 +2172,12 @@ function callStreamClose(stream) { function processHeaders(oldHeaders) { assertIsObject(oldHeaders, 'headers'); - const headers = Object.create(null); + const headers = ObjectCreate(null); if (oldHeaders !== null && oldHeaders !== undefined) { - const hop = hasOwnProperty.bind(oldHeaders); // This loop is here for performance reason. Do not change. for (const key in oldHeaders) { - if (hop(key)) { + if (ObjectPrototypeHasOwnProperty(oldHeaders, key)) { headers[key] = oldHeaders[key]; } } @@ -2353,8 +2357,8 @@ function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) { if (stat.isFile()) { statOptions.length = statOptions.length < 0 ? stat.size - (+statOptions.offset) : - Math.min(stat.size - (+statOptions.offset), - statOptions.length); + MathMin(stat.size - (+statOptions.offset), + statOptions.length); headers[HTTP2_HEADER_CONTENT_LENGTH] = statOptions.length; } @@ -2431,7 +2435,7 @@ class ServerHttp2Stream extends Http2Stream { options.endStream = !!options.endStream; assertIsObject(headers, 'headers'); - headers = Object.assign(Object.create(null), headers); + headers = ObjectAssign(ObjectCreate(null), headers); if (headers[HTTP2_HEADER_METHOD] === undefined) headers[HTTP2_HEADER_METHOD] = HTTP2_METHOD_GET; @@ -2663,7 +2667,7 @@ class ServerHttp2Stream extends Http2Stream { throw new ERR_HTTP2_HEADERS_AFTER_RESPOND(); assertIsObject(headers, 'headers'); - headers = Object.assign(Object.create(null), headers); + headers = ObjectAssign(ObjectCreate(null), headers); debugStreamObj(this, 'sending additional headers'); @@ -2713,8 +2717,8 @@ const setTimeout = { writable: true, value: setStreamTimeout }; -Object.defineProperty(Http2Stream.prototype, 'setTimeout', setTimeout); -Object.defineProperty(Http2Session.prototype, 'setTimeout', setTimeout); +ObjectDefineProperty(Http2Stream.prototype, 'setTimeout', setTimeout); +ObjectDefineProperty(Http2Session.prototype, 'setTimeout', setTimeout); // When the socket emits an error, destroy the associated Http2Session and @@ -2977,7 +2981,7 @@ function connect(authority, options, listener) { } // Support util.promisify -Object.defineProperty(connect, promisify.custom, { +ObjectDefineProperty(connect, promisify.custom, { value: (authority, options) => { return new Promise((resolve) => { const server = connect(authority, options, () => resolve(server)); diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index a0640b242cd8b1..482ae8546ae084 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -1,6 +1,10 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathMax, + ObjectCreate, + ObjectKeys, +} = primordials; const binding = internalBinding('http2'); const { @@ -236,12 +240,12 @@ function updateOptionsBuffer(options) { if (typeof options.maxOutstandingSettings === 'number') { flags |= (1 << IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS); optionsBuffer[IDX_OPTIONS_MAX_OUTSTANDING_SETTINGS] = - Math.max(1, options.maxOutstandingSettings); + MathMax(1, options.maxOutstandingSettings); } if (typeof options.maxSessionMemory === 'number') { flags |= (1 << IDX_OPTIONS_MAX_SESSION_MEMORY); optionsBuffer[IDX_OPTIONS_MAX_SESSION_MEMORY] = - Math.max(1, options.maxSessionMemory); + MathMax(1, options.maxSessionMemory); } optionsBuffer[IDX_OPTIONS_FLAGS] = flags; } @@ -249,7 +253,7 @@ function updateOptionsBuffer(options) { function getDefaultSettings() { settingsBuffer[IDX_SETTINGS_FLAGS] = 0; binding.refreshDefaultSettings(); - const holder = Object.create(null); + const holder = ObjectCreate(null); const flags = settingsBuffer[IDX_SETTINGS_FLAGS]; @@ -430,7 +434,7 @@ function mapToHeaders(map, assertValuePseudoHeader = assertValidPseudoHeader) { let ret = ''; let count = 0; - const keys = Object.keys(map); + const keys = ObjectKeys(map); const singles = new Set(); let i; let isArray; @@ -525,7 +529,7 @@ const assertWithinRange = hideStackFrames( ); function toHeaderObject(headers) { - const obj = Object.create(null); + const obj = ObjectCreate(null); for (var n = 0; n < headers.length; n = n + 2) { const name = headers[n]; let value = headers[n + 1]; diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js index 72caf492223c05..48d7905a39b4e4 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js @@ -3,7 +3,9 @@ // In worker threads, execute the script sent through the // message port. -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const { patchProcessObject, @@ -72,12 +74,12 @@ const port = getEnvMessagePort(); // related IPC properties as unavailable. if (process.env.NODE_CHANNEL_FD) { const workerThreadSetup = require('internal/process/worker_thread_only'); - Object.defineProperty(process, 'channel', { + ObjectDefineProperty(process, 'channel', { enumerable: false, get: workerThreadSetup.unavailable('process.channel') }); - Object.defineProperty(process, 'connected', { + ObjectDefineProperty(process, 'connected', { enumerable: false, get: workerThreadSetup.unavailable('process.connected') }); diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js index 7a9870024515ed..2934ee6148cc2e 100644 --- a/lib/internal/modules/cjs/helpers.js +++ b/lib/internal/modules/cjs/helpers.js @@ -1,6 +1,9 @@ 'use strict'; -const { Object, SafeMap } = primordials; +const { + ObjectDefineProperty, + SafeMap, +} = primordials; const { ERR_MANIFEST_DEPENDENCY_MISSING, ERR_UNKNOWN_BUILTIN_MODULE @@ -140,14 +143,14 @@ function addBuiltinLibsToObject(object) { object[name] = val; }; - Object.defineProperty(object, name, { + ObjectDefineProperty(object, name, { get: () => { const lib = require(name); // Disable the current getter/setter and set up a new // non-enumerable property. delete object[name]; - Object.defineProperty(object, name, { + ObjectDefineProperty(object, name, { get: () => lib, set: setReal, configurable: true, diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index b9587851272b84..3001c23cce49be 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -22,12 +22,18 @@ 'use strict'; const { - JSON, - Object, - ObjectPrototype, - Reflect, + JSONParse, + ObjectCreate, + ObjectDefineProperty, + ObjectFreeze, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ReflectSet, SafeMap, - StringPrototype, + StringPrototypeIndexOf, + StringPrototypeMatch, + StringPrototypeSlice, + StringPrototypeStartsWith, } = primordials; const { NativeModule } = require('internal/bootstrap/loaders'); @@ -91,7 +97,7 @@ const { const isWindows = process.platform === 'win32'; -const relativeResolveCache = Object.create(null); +const relativeResolveCache = ObjectCreate(null); let requireDepth = 0; let statCache = null; @@ -153,12 +159,12 @@ for (const [id, mod] of NativeModule.map) { } } -Object.freeze(builtinModules); +ObjectFreeze(builtinModules); Module.builtinModules = builtinModules; -Module._cache = Object.create(null); -Module._pathCache = Object.create(null); -Module._extensions = Object.create(null); +Module._cache = ObjectCreate(null); +Module._pathCache = ObjectCreate(null); +Module._extensions = ObjectCreate(null); let modulePaths = []; Module.globalPaths = []; @@ -177,16 +183,16 @@ const wrapper = [ let wrapperProxy = new Proxy(wrapper, { set(target, property, value, receiver) { patched = true; - return Reflect.set(target, property, value, receiver); + return ReflectSet(target, property, value, receiver); }, defineProperty(target, property, descriptor) { patched = true; - return Object.defineProperty(target, property, descriptor); + return ObjectDefineProperty(target, property, descriptor); } }); -Object.defineProperty(Module, 'wrap', { +ObjectDefineProperty(Module, 'wrap', { get() { return wrap; }, @@ -197,7 +203,7 @@ Object.defineProperty(Module, 'wrap', { } }); -Object.defineProperty(Module, 'wrapper', { +ObjectDefineProperty(Module, 'wrapper', { get() { return wrapperProxy; }, @@ -242,7 +248,7 @@ function readPackage(requestPath) { } try { - const parsed = JSON.parse(json); + const parsed = JSONParse(json); const filtered = { name: parsed.name, main: parsed.main, @@ -404,7 +410,7 @@ function resolveBasePath(basePath, exts, isMain, trailingSlash, request) { if (!filename) { // Try it with each of the extensions if (exts === undefined) - exts = Object.keys(Module._extensions); + exts = ObjectKeys(Module._extensions); filename = tryExtensions(basePath, exts, isMain); } } @@ -412,7 +418,7 @@ function resolveBasePath(basePath, exts, isMain, trailingSlash, request) { if (!filename && rc === 1) { // Directory. // try it with each of the extensions at "index" if (exts === undefined) - exts = Object.keys(Module._extensions); + exts = ObjectKeys(Module._extensions); filename = tryPackage(basePath, exts, isMain, request); } @@ -430,13 +436,13 @@ function trySelf(parentPath, isMain, request) { let expansion; if (request === pkg.name) { expansion = ''; - } else if (StringPrototype.startsWith(request, `${pkg.name}/`)) { - expansion = StringPrototype.slice(request, pkg.name.length); + } else if (StringPrototypeStartsWith(request, `${pkg.name}/`)) { + expansion = StringPrototypeSlice(request, pkg.name.length); } else { return false; } - const exts = Object.keys(Module._extensions); + const exts = ObjectKeys(Module._extensions); const fromExports = applyExports(basePath, expansion); // Use exports if (fromExports) { @@ -461,7 +467,7 @@ function isConditionalDotExportSugar(exports, basePath) { return false; let isConditional = false; let firstCheck = true; - for (const key of Object.keys(exports)) { + for (const key of ObjectKeys(exports)) { const curIsConditional = key[0] !== '.'; if (firstCheck) { firstCheck = false; @@ -487,7 +493,7 @@ function applyExports(basePath, expansion) { pkgExports = { '.': pkgExports }; if (typeof pkgExports === 'object') { - if (ObjectPrototype.hasOwnProperty(pkgExports, mappingKey)) { + if (ObjectPrototypeHasOwnProperty(pkgExports, mappingKey)) { const mapping = pkgExports[mappingKey]; return resolveExportsTarget(pathToFileURL(basePath + '/'), mapping, '', basePath, mappingKey); @@ -498,17 +504,17 @@ function applyExports(basePath, expansion) { return basePath; let dirMatch = ''; - for (const candidateKey of Object.keys(pkgExports)) { + for (const candidateKey of ObjectKeys(pkgExports)) { if (candidateKey[candidateKey.length - 1] !== '/') continue; if (candidateKey.length > dirMatch.length && - StringPrototype.startsWith(mappingKey, candidateKey)) { + StringPrototypeStartsWith(mappingKey, candidateKey)) { dirMatch = candidateKey; } } if (dirMatch !== '') { const mapping = pkgExports[dirMatch]; - const subpath = StringPrototype.slice(mappingKey, dirMatch.length); + const subpath = StringPrototypeSlice(mappingKey, dirMatch.length); return resolveExportsTarget(pathToFileURL(basePath + '/'), mapping, subpath, basePath, mappingKey); } @@ -532,7 +538,7 @@ function resolveExports(nmPath, request, absoluteRequest) { // The implementation's behavior is meant to mirror resolution in ESM. if (!absoluteRequest) { const [, name, expansion = ''] = - StringPrototype.match(request, EXPORTS_PATTERN) || []; + StringPrototypeMatch(request, EXPORTS_PATTERN) || []; if (!name) { return path.resolve(nmPath, request); } @@ -551,14 +557,14 @@ function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) { const resolvedTarget = new URL(target, pkgPath); const pkgPathPath = pkgPath.pathname; const resolvedTargetPath = resolvedTarget.pathname; - if (StringPrototype.startsWith(resolvedTargetPath, pkgPathPath) && - StringPrototype.indexOf(resolvedTargetPath, '/node_modules/', - pkgPathPath.length - 1) === -1) { + if (StringPrototypeStartsWith(resolvedTargetPath, pkgPathPath) && + StringPrototypeIndexOf(resolvedTargetPath, '/node_modules/', + pkgPathPath.length - 1) === -1) { const resolved = new URL(subpath, resolvedTarget); const resolvedPath = resolved.pathname; - if (StringPrototype.startsWith(resolvedPath, resolvedTargetPath) && - StringPrototype.indexOf(resolvedPath, '/node_modules/', - pkgPathPath.length - 1) === -1) { + if (StringPrototypeStartsWith(resolvedPath, resolvedTargetPath) && + StringPrototypeIndexOf(resolvedPath, '/node_modules/', + pkgPathPath.length - 1) === -1) { return fileURLToPath(resolved); } } @@ -575,7 +581,7 @@ function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) { } } else if (typeof target === 'object' && target !== null) { if (experimentalConditionalExports && - ObjectPrototype.hasOwnProperty(target, 'node')) { + ObjectPrototypeHasOwnProperty(target, 'node')) { try { const result = resolveExportsTarget(pkgPath, target.node, subpath, basePath, mappingKey); @@ -586,7 +592,7 @@ function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) { } } if (experimentalConditionalExports && - ObjectPrototype.hasOwnProperty(target, 'require')) { + ObjectPrototypeHasOwnProperty(target, 'require')) { try { const result = resolveExportsTarget(pkgPath, target.require, subpath, basePath, mappingKey); @@ -596,7 +602,7 @@ function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) { if (e.code !== 'MODULE_NOT_FOUND') throw e; } } - if (ObjectPrototype.hasOwnProperty(target, 'default')) { + if (ObjectPrototypeHasOwnProperty(target, 'default')) { try { return resolveExportsTarget(pkgPath, target.default, subpath, basePath, mappingKey); @@ -674,7 +680,7 @@ Module._findPath = function(request, paths, isMain) { if (!filename) { // Try it with each of the extensions if (exts === undefined) - exts = Object.keys(Module._extensions); + exts = ObjectKeys(Module._extensions); filename = tryExtensions(basePath, exts, isMain); } } @@ -682,7 +688,7 @@ Module._findPath = function(request, paths, isMain) { if (!filename && rc === 1) { // Directory. // try it with each of the extensions at "index" if (exts === undefined) - exts = Object.keys(Module._extensions); + exts = ObjectKeys(Module._extensions); filename = tryPackage(basePath, exts, isMain, request); } @@ -1169,7 +1175,7 @@ Module._extensions['.json'] = function(module, filename) { } try { - module.exports = JSON.parse(stripBOM(content)); + module.exports = JSONParse(stripBOM(content)); } catch (err) { err.message = filename + ': ' + err.message; throw err; diff --git a/lib/internal/modules/esm/create_dynamic_module.js b/lib/internal/modules/esm/create_dynamic_module.js index 804420c92010ed..f8e00fd2ad1889 100644 --- a/lib/internal/modules/esm/create_dynamic_module.js +++ b/lib/internal/modules/esm/create_dynamic_module.js @@ -1,11 +1,16 @@ 'use strict'; -const { ArrayPrototype, JSON, Object } = primordials; +const { + ArrayPrototypeJoin, + ArrayPrototypeMap, + JSONStringify, + ObjectCreate, +} = primordials; const debug = require('internal/util/debuglog').debuglog('esm'); function createImport(impt, index) { - const imptPath = JSON.stringify(impt); + const imptPath = JSONStringify(impt); return `import * as $import_${index} from ${imptPath}; import.meta.imports[${imptPath}] = $import_${index};`; } @@ -23,8 +28,8 @@ import.meta.exports.${name} = { const createDynamicModule = (imports, exports, url = '', evaluate) => { debug('creating ESM facade for %s with exports: %j', url, exports); const source = ` -${ArrayPrototype.join(ArrayPrototype.map(imports, createImport), '\n')} -${ArrayPrototype.join(ArrayPrototype.map(exports, createExport), '\n')} +${ArrayPrototypeJoin(ArrayPrototypeMap(imports, createImport), '\n')} +${ArrayPrototypeJoin(ArrayPrototypeMap(exports, createExport), '\n')} import.meta.done(); `; const { ModuleWrap, callbackMap } = internalBinding('module_wrap'); @@ -32,12 +37,12 @@ import.meta.done(); const readyfns = new Set(); const reflect = { - exports: Object.create(null), + exports: ObjectCreate(null), onReady: (cb) => { readyfns.add(cb); }, }; if (imports.length) - reflect.imports = Object.create(null); + reflect.imports = ObjectCreate(null); callbackMap.set(m, { initializeImportMeta: (meta, wrap) => { diff --git a/lib/internal/modules/esm/default_resolve.js b/lib/internal/modules/esm/default_resolve.js index ab751da5eab512..749f6861cd3ee6 100644 --- a/lib/internal/modules/esm/default_resolve.js +++ b/lib/internal/modules/esm/default_resolve.js @@ -1,5 +1,9 @@ 'use strict'; +const { + SafeMap, +} = primordials; + const internalFS = require('internal/fs/utils'); const { NativeModule } = require('internal/bootstrap/loaders'); const { extname } = require('path'); @@ -20,8 +24,6 @@ const { ERR_INPUT_TYPE_NOT_ALLOWED, ERR_UNKNOWN_FILE_EXTENSION, ERR_UNSUPPORTED_ESM_URL_SCHEME } = require('internal/errors').codes; -const { SafeMap } = primordials; - const realpathCache = new SafeMap(); // const TYPE_NONE = 0; diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 644c13dbe5d6cb..255e5d2aba7bd8 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -1,6 +1,10 @@ 'use strict'; -const { FunctionPrototype } = primordials; +const { + FunctionPrototypeBind, + ObjectSetPrototypeOf, + SafeMap, +} = primordials; const { ERR_INVALID_RETURN_PROPERTY, @@ -25,11 +29,6 @@ const { getOptionValue } = require('internal/options'); const debug = require('internal/util/debuglog').debuglog('esm'); -const { - Object, - SafeMap -} = primordials; - /* A Loader instance is used as the main entry point for loading ES modules. * Currently, this is a singleton -- there is only one used for loading * the main module and everything in its dependency graph. */ @@ -146,10 +145,10 @@ class Loader { hook({ resolve, dynamicInstantiate }) { // Use .bind() to avoid giving access to the Loader instance when called. if (resolve !== undefined) - this._resolve = FunctionPrototype.bind(resolve, null); + this._resolve = FunctionPrototypeBind(resolve, null); if (dynamicInstantiate !== undefined) { this._dynamicInstantiate = - FunctionPrototype.bind(dynamicInstantiate, null); + FunctionPrototypeBind(dynamicInstantiate, null); } } @@ -191,6 +190,6 @@ class Loader { } } -Object.setPrototypeOf(Loader.prototype, null); +ObjectSetPrototypeOf(Loader.prototype, null); exports.Loader = Loader; diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index df1edc3810c080..e4a9040217689d 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -1,9 +1,9 @@ 'use strict'; const { - Object, + ObjectSetPrototypeOf, SafeSet, - SafePromise + SafePromise, } = primordials; const { ModuleWrap } = internalBinding('module_wrap'); @@ -109,5 +109,5 @@ class ModuleJob { return { module, result: module.evaluate(timeout, breakOnSigint) }; } } -Object.setPrototypeOf(ModuleJob.prototype, null); +ObjectSetPrototypeOf(ModuleJob.prototype, null); module.exports = ModuleJob; diff --git a/lib/internal/modules/esm/module_map.js b/lib/internal/modules/esm/module_map.js index 41adc0079ada31..9b7d86581e4159 100644 --- a/lib/internal/modules/esm/module_map.js +++ b/lib/internal/modules/esm/module_map.js @@ -2,7 +2,7 @@ const ModuleJob = require('internal/modules/esm/module_job'); const { - SafeMap + SafeMap, } = primordials; const debug = require('internal/util/debuglog').debuglog('esm'); const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 2fa9d631ee2ec9..99e4c014053202 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -3,10 +3,10 @@ /* global WebAssembly */ const { - JSON, - Object, + JSONParse, + ObjectKeys, SafeMap, - StringPrototype + StringPrototypeReplace, } = primordials; const { Buffer } = require('buffer'); @@ -29,7 +29,6 @@ const { ERR_UNKNOWN_BUILTIN_MODULE } = require('internal/errors').codes; const readFileAsync = promisify(fs.readFile); -const JsonParse = JSON.parse; const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache'); const moduleWrap = internalBinding('module_wrap'); const { ModuleWrap } = moduleWrap; @@ -101,7 +100,7 @@ translators.set('commonjs', function commonjsStrategy(url, isMain) { return cached; } const module = CJSModule._cache[ - isWindows ? StringPrototype.replace(pathname, winSepRegEx, '\\') : pathname + isWindows ? StringPrototypeReplace(pathname, winSepRegEx, '\\') : pathname ]; if (module && module.loaded) { const exports = module.exports; @@ -142,7 +141,7 @@ translators.set('json', async function jsonStrategy(url) { let module; if (pathname) { modulePath = isWindows ? - StringPrototype.replace(pathname, winSepRegEx, '\\') : pathname; + StringPrototypeReplace(pathname, winSepRegEx, '\\') : pathname; module = CJSModule._cache[modulePath]; if (module && module.loaded) { const exports = module.exports; @@ -165,7 +164,7 @@ translators.set('json', async function jsonStrategy(url) { } } try { - const exports = JsonParse(stripBOM(content)); + const exports = JSONParse(stripBOM(content)); module = { exports, loaded: true @@ -206,7 +205,7 @@ translators.set('wasm', async function(url) { return createDynamicModule(imports, exports, url, (reflect) => { const { exports } = new WebAssembly.Instance(compiled, reflect.imports); - for (const expt of Object.keys(exports)) + for (const expt of ObjectKeys(exports)) reflect.exports[expt].set(exports[expt]); }).module; }); diff --git a/lib/internal/per_context/domexception.js b/lib/internal/per_context/domexception.js index 3852567ac6bdba..9b26631904284a 100644 --- a/lib/internal/per_context/domexception.js +++ b/lib/internal/per_context/domexception.js @@ -1,10 +1,11 @@ 'use strict'; const { + ObjectDefineProperties, + ObjectDefineProperty, SafeWeakMap, SafeMap, - Object, - Symbol + SymbolToStringTag, } = primordials; class ERR_INVALID_THIS extends TypeError { @@ -73,8 +74,8 @@ class DOMException extends Error { } } -Object.defineProperties(DOMException.prototype, { - [Symbol.toStringTag]: { configurable: true, value: 'DOMException' }, +ObjectDefineProperties(DOMException.prototype, { + [SymbolToStringTag]: { configurable: true, value: 'DOMException' }, name: { enumerable: true, configurable: true }, message: { enumerable: true, configurable: true }, code: { enumerable: true, configurable: true } @@ -112,8 +113,8 @@ function forEachCode(fn) { forEachCode((name, codeName, value) => { const desc = { enumerable: true, value }; - Object.defineProperty(DOMException, codeName, desc); - Object.defineProperty(DOMException.prototype, codeName, desc); + ObjectDefineProperty(DOMException, codeName, desc); + ObjectDefineProperty(DOMException.prototype, codeName, desc); }); exports.DOMException = DOMException; diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 7e02a9e3162d9c..6957019490c6bf 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -37,14 +37,28 @@ function copyProps(src, dest) { } } -function copyPrototype(src, dest) { +function copyPropsRenamed(src, dest, prefix) { for (const key of Reflect.ownKeys(src)) { - if (!Reflect.getOwnPropertyDescriptor(dest, key)) { + if (typeof key === 'string') { + Reflect.defineProperty( + dest, + `${prefix}${key[0].toUpperCase()}${key.slice(1)}`, + Reflect.getOwnPropertyDescriptor(src, key)); + } + } +} + +function copyPrototype(src, dest, prefix) { + for (const key of Reflect.ownKeys(src)) { + if (typeof key === 'string') { const desc = Reflect.getOwnPropertyDescriptor(src, key); if (typeof desc.value === 'function') { desc.value = uncurryThis(desc.value); } - Reflect.defineProperty(dest, key, desc); + Reflect.defineProperty( + dest, + `${prefix}${key[0].toUpperCase()}${key.slice(1)}`, + desc); } } } @@ -83,13 +97,13 @@ primordials.SafePromise = makeSafe( 'Math', 'Reflect' ].forEach((name) => { - const target = primordials[name] = Object.create(null); - copyProps(global[name], target); + copyPropsRenamed(global[name], primordials, name); }); // Create copies of intrinsic objects [ 'Array', + 'ArrayBuffer', 'BigInt', 'Boolean', 'Date', @@ -102,18 +116,19 @@ primordials.SafePromise = makeSafe( 'Set', 'String', 'Symbol', + 'WeakMap', + 'WeakSet', ].forEach((name) => { const original = global[name]; - const target = primordials[name] = Object.setPrototypeOf({ + primordials[name] = Object.setPrototypeOf({ [name]: function(...args) { return new.target ? ReflectConstruct(original, args, new.target) : ReflectApply(original, this, args); } }[name], null); - copyProps(original, target); - const proto = primordials[name + 'Prototype'] = Object.create(null); - copyPrototype(original.prototype, proto); + copyPropsRenamed(original, primordials, name); + copyPrototype(original.prototype, primordials, `${name}Prototype`); }); Object.setPrototypeOf(primordials, null); diff --git a/lib/internal/policy/manifest.js b/lib/internal/policy/manifest.js index e8400b672e57b0..d078ed092e22a7 100644 --- a/lib/internal/policy/manifest.js +++ b/lib/internal/policy/manifest.js @@ -2,11 +2,13 @@ const { Map, - MapPrototype, - Object, - RegExpPrototype, + MapPrototypeSet, + ObjectEntries, + ObjectFreeze, + ObjectSetPrototypeOf, + RegExpPrototypeTest, SafeMap, - uncurryThis + uncurryThis, } = primordials; const { canBeRequiredByUsers @@ -28,7 +30,6 @@ const HashUpdate = uncurryThis(crypto.Hash.prototype.update); const HashDigest = uncurryThis(crypto.Hash.prototype.digest); const BufferEquals = uncurryThis(Buffer.prototype.equals); const BufferToString = uncurryThis(Buffer.prototype.toString); -const { entries } = Object; const kRelativeURLStringPattern = /^\.{0,2}\//; const { getOptionValue } = require('internal/options'); const shouldAbortOnUncaughtException = @@ -73,7 +74,7 @@ class Manifest { } this.#reaction = reaction; - const manifestEntries = entries(obj.resources); + const manifestEntries = ObjectEntries(obj.resources); const parsedURLs = new SafeMap(); for (let i = 0; i < manifestEntries.length; i++) { @@ -84,7 +85,7 @@ class Manifest { resourceURL = parsedURLs.get(resourceHREF); resourceHREF = resourceURL.href; } else if ( - RegExpPrototype.test(kRelativeURLStringPattern, resourceHREF) + RegExpPrototypeTest(kRelativeURLStringPattern, resourceHREF) ) { resourceURL = new URL(resourceHREF, manifestURL); resourceHREF = resourceURL.href; @@ -96,7 +97,7 @@ class Manifest { if (integrity != null) { debug(`Manifest contains integrity for url ${originalHREF}`); if (typeof integrity === 'string') { - const sri = Object.freeze(SRI.parse(integrity)); + const sri = ObjectFreeze(SRI.parse(integrity)); if (integrities.has(resourceHREF)) { const old = integrities.get(resourceHREF); let mismatch = false; @@ -156,7 +157,7 @@ class Manifest { parsedURLs.set(to, resolvedURL); parsedURLs.set(href, resolvedURL); return resolvedURL; - } else if (RegExpPrototype.test(kRelativeURLStringPattern, to)) { + } else if (RegExpPrototypeTest(kRelativeURLStringPattern, to)) { const resolvedURL = new URL(to, manifestURL); const href = resourceURL.href; parsedURLs.set(to, resolvedURL); @@ -180,7 +181,7 @@ class Manifest { 'dependencies'); } } - Object.freeze(this); + ObjectFreeze(this); } getRedirector(requester) { @@ -217,7 +218,7 @@ class Manifest { timingSafeEqual(digest, expected)) { return true; } - MapPrototype.set( + MapPrototypeSet( realIntegrities, algorithm, BufferToString(digest, 'base64') @@ -230,8 +231,8 @@ class Manifest { } // Lock everything down to avoid problems even if reference is leaked somehow -Object.setPrototypeOf(Manifest, null); -Object.setPrototypeOf(Manifest.prototype, null); -Object.freeze(Manifest); -Object.freeze(Manifest.prototype); -module.exports = Object.freeze({ Manifest }); +ObjectSetPrototypeOf(Manifest, null); +ObjectSetPrototypeOf(Manifest.prototype, null); +ObjectFreeze(Manifest); +ObjectFreeze(Manifest.prototype); +module.exports = ObjectFreeze({ Manifest }); diff --git a/lib/internal/policy/sri.js b/lib/internal/policy/sri.js index 877c96a6f7b7d6..38d7fc9e07d741 100644 --- a/lib/internal/policy/sri.js +++ b/lib/internal/policy/sri.js @@ -2,9 +2,12 @@ // Value of https://w3c.github.io/webappsec-subresource-integrity/#the-integrity-attribute const { - Object, - RegExpPrototype, - StringPrototype + ObjectDefineProperty, + ObjectFreeze, + ObjectSeal, + RegExpPrototypeExec, + RegExpPrototypeTest, + StringPrototypeSlice, } = primordials; // Returns [{algorithm, value (in base64 string), options,}] @@ -20,10 +23,9 @@ const kHASH_EXPRESSION = `(${kHASH_ALGO})-(${kHASH_VALUE})`; const kOPTION_EXPRESSION = `(${kVCHAR}*)`; const kHASH_WITH_OPTIONS = `${kHASH_EXPRESSION}(?:[?](${kOPTION_EXPRESSION}))?`; const kSRIPattern = RegExp(`(${kWSP}*)(?:${kHASH_WITH_OPTIONS})`, 'g'); -const { freeze } = Object; -Object.seal(kSRIPattern); +ObjectSeal(kSRIPattern); const kAllWSP = RegExp(`^${kWSP}*$`); -Object.seal(kAllWSP); +ObjectSeal(kAllWSP); const BufferFrom = require('buffer').Buffer.from; @@ -32,7 +34,7 @@ const parse = (str) => { let prevIndex = 0; let match; const entries = []; - while (match = RegExpPrototype.exec(kSRIPattern, str)) { + while (match = RegExpPrototypeExec(kSRIPattern, str)) { if (match.index !== prevIndex) { throw new ERR_SRI_PARSE(str, str.charAt(prevIndex), prevIndex); } @@ -41,10 +43,10 @@ const parse = (str) => { } // Avoid setters being fired - Object.defineProperty(entries, entries.length, { + ObjectDefineProperty(entries, entries.length, { enumerable: true, configurable: true, - value: freeze({ + value: ObjectFreeze({ __proto__: null, algorithm: match[2], value: BufferFrom(match[3], 'base64'), @@ -55,7 +57,7 @@ const parse = (str) => { } if (prevIndex !== str.length) { - if (!RegExpPrototype.test(kAllWSP, StringPrototype.slice(str, prevIndex))) { + if (!RegExpPrototypeTest(kAllWSP, StringPrototypeSlice(str, prevIndex))) { throw new ERR_SRI_PARSE(str, str.charAt(prevIndex), prevIndex); } } diff --git a/lib/internal/process/execution.js b/lib/internal/process/execution.js index 8e8c46872114cb..8b15fbbae46f26 100644 --- a/lib/internal/process/execution.js +++ b/lib/internal/process/execution.js @@ -1,6 +1,8 @@ 'use strict'; -const { JSON } = primordials; +const { + JSONStringify, +} = primordials; const path = require('path'); @@ -70,7 +72,7 @@ function evalScript(name, body, breakFirstLine, print) { const baseUrl = pathToFileURL(module.filename).href; const script = ` - global.__filename = ${JSON.stringify(name)}; + global.__filename = ${JSONStringify(name)}; global.exports = exports; global.module = module; global.__dirname = __dirname; @@ -79,13 +81,13 @@ function evalScript(name, body, breakFirstLine, print) { delete global.kVmBreakFirstLineSymbol; delete global.asyncESM; return require("vm").runInThisContext( - ${JSON.stringify(body)}, { - filename: ${JSON.stringify(name)}, + ${JSONStringify(body)}, { + filename: ${JSONStringify(name)}, displayErrors: true, [kVmBreakFirstLineSymbol]: ${!!breakFirstLine}, async importModuleDynamically (specifier) { const loader = await asyncESM.ESMLoader; - return loader.import(specifier, ${JSON.stringify(baseUrl)}); + return loader.import(specifier, ${JSONStringify(baseUrl)}); } });\n`; const result = module._compile(script, `${name}-wrapper`); diff --git a/lib/internal/process/per_thread.js b/lib/internal/process/per_thread.js index f3a47744ccd187..624601303a4460 100644 --- a/lib/internal/process/per_thread.js +++ b/lib/internal/process/per_thread.js @@ -5,10 +5,13 @@ // thread and the worker threads. const { - Object, - RegExpPrototype, - SetPrototype, - StringPrototype + ObjectDefineProperties, + ObjectDefineProperty, + ObjectFreeze, + ObjectGetOwnPropertyDescriptors, + RegExpPrototypeTest, + SetPrototypeHas, + StringPrototypeReplace, } = primordials; const { @@ -271,15 +274,15 @@ function buildAllowedFlags() { } const trimLeadingDashes = - (flag) => StringPrototype.replace(flag, leadingDashesRegex, ''); + (flag) => StringPrototypeReplace(flag, leadingDashesRegex, ''); // Save these for comparison against flags provided to // process.allowedNodeEnvironmentFlags.has() which lack leading dashes. // Avoid interference w/ user code by flattening `Set.prototype` into // each object. - const nodeFlags = Object.defineProperties( + const nodeFlags = ObjectDefineProperties( new Set(allowedNodeEnvironmentFlags.map(trimLeadingDashes)), - Object.getOwnPropertyDescriptors(Set.prototype) + ObjectGetOwnPropertyDescriptors(Set.prototype) ); class NodeEnvironmentFlagsSet extends Set { @@ -288,7 +291,7 @@ function buildAllowedFlags() { // The super constructor consumes `add`, but // disallow any future adds. - Object.defineProperty(this, 'add', { + ObjectDefineProperty(this, 'add', { value: () => this }); } @@ -311,21 +314,21 @@ function buildAllowedFlags() { // on a dummy option set and see whether it rejects the argument or // not. if (typeof key === 'string') { - key = StringPrototype.replace(key, replaceUnderscoresRegex, '-'); - if (RegExpPrototype.test(leadingDashesRegex, key)) { - key = StringPrototype.replace(key, trailingValuesRegex, ''); - return SetPrototype.has(this, key); + key = StringPrototypeReplace(key, replaceUnderscoresRegex, '-'); + if (RegExpPrototypeTest(leadingDashesRegex, key)) { + key = StringPrototypeReplace(key, trailingValuesRegex, ''); + return SetPrototypeHas(this, key); } - return SetPrototype.has(nodeFlags, key); + return SetPrototypeHas(nodeFlags, key); } return false; } } - Object.freeze(NodeEnvironmentFlagsSet.prototype.constructor); - Object.freeze(NodeEnvironmentFlagsSet.prototype); + ObjectFreeze(NodeEnvironmentFlagsSet.prototype.constructor); + ObjectFreeze(NodeEnvironmentFlagsSet.prototype); - return Object.freeze(new NodeEnvironmentFlagsSet( + return ObjectFreeze(new NodeEnvironmentFlagsSet( allowedNodeEnvironmentFlags )); } diff --git a/lib/internal/process/policy.js b/lib/internal/process/policy.js index d2501403c39951..ea283a449742fc 100644 --- a/lib/internal/process/policy.js +++ b/lib/internal/process/policy.js @@ -1,6 +1,10 @@ 'use strict'; -const { JSON, Object, Reflect } = primordials; +const { + JSONParse, + ObjectFreeze, + ReflectSetPrototypeOf, +} = primordials; const { ERR_MANIFEST_TDZ, @@ -10,7 +14,7 @@ let manifest; let manifestSrc; let manifestURL; -module.exports = Object.freeze({ +module.exports = ObjectFreeze({ __proto__: null, setup(src, url) { manifestSrc = src; @@ -20,10 +24,10 @@ module.exports = Object.freeze({ return; } - const json = JSON.parse(src, (_, o) => { + const json = JSONParse(src, (_, o) => { if (o && typeof o === 'object') { - Reflect.setPrototypeOf(o, null); - Object.freeze(o); + ReflectSetPrototypeOf(o, null); + ObjectFreeze(o); } return o; }); diff --git a/lib/internal/process/promises.js b/lib/internal/process/promises.js index 5128b98f5a1e7e..e2a589a802682d 100644 --- a/lib/internal/process/promises.js +++ b/lib/internal/process/promises.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, +} = primordials; const { tickInfo, @@ -226,7 +228,7 @@ function getErrorWithoutStack(name, message) { // eslint-disable-next-line no-restricted-syntax const err = new Error(message); Error.stackTraceLimit = tmp; - Object.defineProperty(err, 'name', { + ObjectDefineProperty(err, 'name', { value: name, enumerable: false, writable: true, diff --git a/lib/internal/process/report.js b/lib/internal/process/report.js index cc78aebbdaa358..407cc12cb04f76 100644 --- a/lib/internal/process/report.js +++ b/lib/internal/process/report.js @@ -5,7 +5,9 @@ const { } = require('internal/errors').codes; const { validateSignalName, validateString } = require('internal/validators'); const nr = internalBinding('report'); -const { JSON } = primordials; +const { + JSONParse, +} = primordials; const report = { writeReport(file, err) { if (typeof file === 'object' && file !== null) { @@ -27,7 +29,7 @@ const report = { else if (err === null || typeof err !== 'object') throw new ERR_INVALID_ARG_TYPE('err', 'Object', err); - return JSON.parse(nr.getReport(err.stack)); + return JSONParse(nr.getReport(err.stack)); }, get directory() { return nr.getDirectory(); diff --git a/lib/internal/process/task_queues.js b/lib/internal/process/task_queues.js index 3deebaaa076eb2..7f353ff0e248e5 100644 --- a/lib/internal/process/task_queues.js +++ b/lib/internal/process/task_queues.js @@ -1,6 +1,8 @@ 'use strict'; -const { FunctionPrototype } = primordials; +const { + FunctionPrototypeBind, +} = primordials; const { // For easy access to the nextTick state in the C++ land, @@ -166,7 +168,7 @@ function queueMicrotask(callback) { const asyncResource = createMicrotaskResource(); asyncResource.callback = callback; - enqueueMicrotask(FunctionPrototype.bind(runMicrotask, asyncResource)); + enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource)); } module.exports = { diff --git a/lib/internal/repl.js b/lib/internal/repl.js index cb368ea6121ec3..a5f5cd25f25561 100644 --- a/lib/internal/repl.js +++ b/lib/internal/repl.js @@ -1,11 +1,13 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, +} = primordials; const REPL = require('repl'); const { kStandaloneREPL } = require('internal/repl/utils'); -module.exports = Object.create(REPL); +module.exports = ObjectCreate(REPL); module.exports.createInternalRepl = createRepl; function createRepl(env, opts, cb) { diff --git a/lib/internal/repl/await.js b/lib/internal/repl/await.js index 1c7dba2efdf2d6..b437221ca22e77 100644 --- a/lib/internal/repl/await.js +++ b/lib/internal/repl/await.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectKeys, +} = primordials; const acorn = require('internal/deps/acorn/acorn/dist/acorn'); const walk = require('internal/deps/acorn/acorn-walk/dist/walk'); @@ -72,7 +74,7 @@ const visitorsWithoutAncestors = { }; const visitors = {}; -for (const nodeType of Object.keys(walk.base)) { +for (const nodeType of ObjectKeys(walk.base)) { const callback = visitorsWithoutAncestors[nodeType] || walk.base[nodeType]; visitors[nodeType] = (node, state, c) => { const isNew = node !== state.ancestors[state.ancestors.length - 1]; diff --git a/lib/internal/source_map/source_map_cache.js b/lib/internal/source_map/source_map_cache.js index 340615eb6cffcd..8211e51e3ec413 100644 --- a/lib/internal/source_map/source_map_cache.js +++ b/lib/internal/source_map/source_map_cache.js @@ -1,26 +1,21 @@ 'use strict'; const { - JSON, - Object: { - create: ObjectCreate, - keys: ObjectKeys, - getOwnPropertyDescriptor: ObjectGetOwnPropertyDescriptor, - }, - ObjectPrototype: { - hasOwnProperty: ObjectHasOwnProperty - }, - MapPrototype: { - entries: MapEntries - }, uncurryThis + JSONParse, + ObjectCreate, + ObjectKeys, + ObjectGetOwnPropertyDescriptor, + ObjectPrototypeHasOwnProperty, + MapPrototypeEntries, + WeakMapPrototypeGet, + uncurryThis, } = primordials; -const MapIteratorNext = uncurryThis(MapEntries(new Map()).next); -const WeakMapGet = uncurryThis(WeakMap.prototype.get); +const MapIteratorNext = uncurryThis(MapPrototypeEntries(new Map()).next); function ObjectGetValueSafe(obj, key) { const desc = ObjectGetOwnPropertyDescriptor(obj, key); - return ObjectHasOwnProperty(desc, 'value') ? desc.value : undefined; + return ObjectPrototypeHasOwnProperty(desc, 'value') ? desc.value : undefined; } // See https://sourcemaps.info/spec.html for SourceMap V3 specification. @@ -115,7 +110,7 @@ function lineLengths(content) { function sourceMapFromFile(sourceMapFile) { try { const content = fs.readFileSync(sourceMapFile, 'utf8'); - const data = JSON.parse(content); + const data = JSONParse(content); return sourcesToAbsolute(dirname(sourceMapFile), data); } catch (err) { debug(err.stack); @@ -134,7 +129,7 @@ function sourceMapFromDataUrl(basePath, url) { const decodedData = base64 ? Buffer.from(data, 'base64').toString('utf8') : data; try { - const parsedData = JSON.parse(decodedData); + const parsedData = JSONParse(decodedData); return sourcesToAbsolute(basePath, parsedData); } catch (err) { debug(err.stack); @@ -182,7 +177,7 @@ function rekeySourceMap(cjsModuleInstance, newInstance) { function sourceMapCacheToObject() { const obj = ObjectCreate(null); - const it = MapEntries(esmSourceMapCache); + const it = MapPrototypeEntries(esmSourceMapCache); let entry; while (!(entry = MapIteratorNext(it)).done) { const k = entry.value[0]; @@ -211,7 +206,7 @@ function appendCJSCache(obj) { for (let i = 0; i < cjsModules.length; i++) { const key = cjsModules[i]; const module = ObjectGetValueSafe(cjsModuleCache, key); - const value = WeakMapGet(cjsSourceMapCache, module); + const value = WeakMapPrototypeGet(cjsSourceMapCache, module); if (value) { // This is okay because `obj` has a null prototype. obj[`file://${key}`] = { diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 07f2191e7134ce..e05813e5dfd947 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -1,6 +1,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, + ObjectGetPrototypeOf, + ObjectSetPrototypeOf, +} = primordials; const finished = require('internal/streams/end-of-stream'); @@ -49,10 +53,10 @@ function wrapForNext(lastPromise, iter) { }; } -const AsyncIteratorPrototype = Object.getPrototypeOf( - Object.getPrototypeOf(async function* () {}).prototype); +const AsyncIteratorPrototype = ObjectGetPrototypeOf( + ObjectGetPrototypeOf(async function* () {}).prototype); -const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({ +const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({ get stream() { return this[kStream]; }, @@ -135,7 +139,7 @@ const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({ }, AsyncIteratorPrototype); const createReadableStreamAsyncIterator = (stream) => { - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype, { + const iterator = ObjectCreate(ReadableStreamAsyncIteratorPrototype, { [kStream]: { value: stream, writable: true }, [kLastResolve]: { value: null, writable: true }, [kLastReject]: { value: null, writable: true }, diff --git a/lib/internal/streams/lazy_transform.js b/lib/internal/streams/lazy_transform.js index 0036bf306c3193..6584159095af39 100644 --- a/lib/internal/streams/lazy_transform.js +++ b/lib/internal/streams/lazy_transform.js @@ -3,7 +3,11 @@ // for the stream, one conventional and one non-conventional. 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperties, + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const stream = require('stream'); @@ -18,8 +22,8 @@ function LazyTransform(options) { this.writable = true; this.readable = true; } -Object.setPrototypeOf(LazyTransform.prototype, stream.Transform.prototype); -Object.setPrototypeOf(LazyTransform, stream.Transform); +ObjectSetPrototypeOf(LazyTransform.prototype, stream.Transform.prototype); +ObjectSetPrototypeOf(LazyTransform, stream.Transform); function makeGetter(name) { return function() { @@ -36,7 +40,7 @@ function makeGetter(name) { function makeSetter(name) { return function(val) { - Object.defineProperty(this, name, { + ObjectDefineProperty(this, name, { value: val, enumerable: true, configurable: true, @@ -45,7 +49,7 @@ function makeSetter(name) { }; } -Object.defineProperties(LazyTransform.prototype, { +ObjectDefineProperties(LazyTransform.prototype, { _readableState: { get: makeGetter('_readableState'), set: makeSetter('_readableState'), diff --git a/lib/internal/streams/legacy.js b/lib/internal/streams/legacy.js index 062eabec3890c0..702e3c56ba6376 100644 --- a/lib/internal/streams/legacy.js +++ b/lib/internal/streams/legacy.js @@ -1,14 +1,16 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const EE = require('events'); function Stream() { EE.call(this); } -Object.setPrototypeOf(Stream.prototype, EE.prototype); -Object.setPrototypeOf(Stream, EE); +ObjectSetPrototypeOf(Stream.prototype, EE.prototype); +ObjectSetPrototypeOf(Stream, EE); Stream.prototype.pipe = function(dest, options) { const source = this; diff --git a/lib/internal/streams/state.js b/lib/internal/streams/state.js index a3f5e672862452..aa16a0a6b8afb7 100644 --- a/lib/internal/streams/state.js +++ b/lib/internal/streams/state.js @@ -1,6 +1,8 @@ 'use strict'; -const { Math } = primordials; +const { + MathFloor, +} = primordials; const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes; @@ -20,7 +22,7 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) { const name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } - return Math.floor(hwm); + return MathFloor(hwm); } // Default value diff --git a/lib/internal/timers.js b/lib/internal/timers.js index 4067c2ee0b3165..e55e17b53702a1 100644 --- a/lib/internal/timers.js +++ b/lib/internal/timers.js @@ -72,7 +72,11 @@ // timers within (or creation of a new list). However, these operations combined // have shown to be trivial in comparison to other timers architectures. -const { Math, Object } = primordials; +const { + MathMax, + MathTrunc, + ObjectCreate, +} = primordials; const { scheduleTimer, @@ -137,7 +141,7 @@ const timerListQueue = new PriorityQueue(compareTimersLists, setPosition); // // - key = time in milliseconds // - value = linked list -const timerListMap = Object.create(null); +const timerListMap = ObjectCreate(null); function initAsyncResource(resource, type) { const asyncId = resource[async_id_symbol] = newAsyncId(); @@ -308,7 +312,7 @@ function insert(item, refed, start) { return; // Truncate so that accuracy of sub-millisecond timers is not assumed. - msecs = Math.trunc(msecs); + msecs = MathTrunc(msecs); item._idleStart = start; @@ -490,7 +494,7 @@ function getTimerCallbacks(runNextTicks) { // Check if this loop iteration is too early for the next timer. // This happens if there are more timers scheduled for later in the list. if (diff < msecs) { - list.expiry = Math.max(timer._idleStart + msecs, now + 1); + list.expiry = MathMax(timer._idleStart + msecs, now + 1); list.id = timerListId++; timerListQueue.percolateDown(1); debug('%d list wait because diff is %d', msecs, diff); diff --git a/lib/internal/tls.js b/lib/internal/tls.js index 8bf9330352bd20..ee438016380fbd 100644 --- a/lib/internal/tls.js +++ b/lib/internal/tls.js @@ -1,11 +1,13 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, +} = primordials; // Example: // C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=ry@clouds.org function parseCertString(s) { - const out = Object.create(null); + const out = ObjectCreate(null); const parts = s.split('\n'); for (let i = 0, len = parts.length; i < len; i++) { const sepIndex = parts[i].indexOf('='); diff --git a/lib/internal/trace_events_async_hooks.js b/lib/internal/trace_events_async_hooks.js index 4485b7a8c820a0..87ee63d8ba7426 100644 --- a/lib/internal/trace_events_async_hooks.js +++ b/lib/internal/trace_events_async_hooks.js @@ -1,6 +1,10 @@ 'use strict'; -const { Object, SafeMap, SafeSet } = primordials; +const { + ObjectKeys, + SafeMap, + SafeSet, +} = primordials; const { trace } = internalBinding('trace_events'); const async_wrap = internalBinding('async_wrap'); @@ -20,7 +24,7 @@ const kEnabled = Symbol('enabled'); // Embedder C++ API can't be emitted from async_wrap.cc. Thus they are // emitted using the JavaScript API. To prevent emitting the same event // twice the async_wrap.Providers list is used to filter the events. -const nativeProviders = new SafeSet(Object.keys(async_wrap.Providers)); +const nativeProviders = new SafeSet(ObjectKeys(async_wrap.Providers)); const typeMemory = new SafeMap(); function createHook() { diff --git a/lib/internal/url.js b/lib/internal/url.js index 860fa4d7ad01b3..b4c047be529515 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1,6 +1,15 @@ 'use strict'; -const { Object, Reflect } = primordials; +const { + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectGetOwnPropertySymbols, + ObjectGetPrototypeOf, + ObjectKeys, + ReflectGetOwnPropertyDescriptor, + ReflectOwnKeys, +} = primordials; const { inspect } = require('internal/util/inspect'); const { @@ -74,8 +83,8 @@ const searchParams = Symbol('query'); const kFormat = Symbol('format'); // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object -const IteratorPrototype = Object.getPrototypeOf( - Object.getPrototypeOf([][Symbol.iterator]()) +const IteratorPrototype = ObjectGetPrototypeOf( + ObjectGetPrototypeOf([][Symbol.iterator]()) ); const unpairedSurrogateRe = @@ -164,10 +173,10 @@ class URLSearchParams { // Record // Need to use reflection APIs for full spec compliance. this[searchParams] = []; - const keys = Reflect.ownKeys(init); + const keys = ReflectOwnKeys(init); for (let i = 0; i < keys.length; i++) { const key = keys[i]; - const desc = Reflect.getOwnPropertyDescriptor(init, key); + const desc = ReflectGetOwnPropertyDescriptor(init, key); if (desc !== undefined && desc.enumerable) { const typedKey = toUSVString(key); const typedValue = toUSVString(init[key]); @@ -338,7 +347,7 @@ class URL { [inspect.custom](depth, opts) { if (this == null || - Object.getPrototypeOf(this[context]) !== URLContext.prototype) { + ObjectGetPrototypeOf(this[context]) !== URLContext.prototype) { throw new ERR_INVALID_THIS('URL'); } @@ -347,7 +356,7 @@ class URL { const ctor = getConstructorOf(this); - const obj = Object.create({ + const obj = ObjectCreate({ constructor: ctor === null ? URL : ctor }); @@ -374,7 +383,7 @@ class URL { } } -Object.defineProperties(URL.prototype, { +ObjectDefineProperties(URL.prototype, { [kFormat]: { enumerable: false, configurable: false, @@ -846,7 +855,7 @@ function serializeParams(array) { // Mainly to mitigate func-name-matching ESLint rule function defineIDLClass(proto, classStr, obj) { // https://heycam.github.io/webidl/#dfn-class-string - Object.defineProperty(proto, Symbol.toStringTag, { + ObjectDefineProperty(proto, Symbol.toStringTag, { writable: false, enumerable: false, configurable: true, @@ -854,16 +863,16 @@ function defineIDLClass(proto, classStr, obj) { }); // https://heycam.github.io/webidl/#es-operations - for (const key of Object.keys(obj)) { - Object.defineProperty(proto, key, { + for (const key of ObjectKeys(obj)) { + ObjectDefineProperty(proto, key, { writable: true, enumerable: true, configurable: true, value: obj[key] }); } - for (const key of Object.getOwnPropertySymbols(obj)) { - Object.defineProperty(proto, key, { + for (const key of ObjectGetOwnPropertySymbols(obj)) { + ObjectDefineProperty(proto, key, { writable: true, enumerable: false, configurable: true, @@ -1137,7 +1146,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { }); // https://heycam.github.io/webidl/#es-iterable-entries -Object.defineProperty(URLSearchParams.prototype, Symbol.iterator, { +ObjectDefineProperty(URLSearchParams.prototype, Symbol.iterator, { writable: true, configurable: true, value: URLSearchParams.prototype.entries @@ -1145,7 +1154,7 @@ Object.defineProperty(URLSearchParams.prototype, Symbol.iterator, { // https://heycam.github.io/webidl/#dfn-default-iterator-object function createSearchParamsIterator(target, kind) { - const iterator = Object.create(URLSearchParamsIteratorPrototype); + const iterator = ObjectCreate(URLSearchParamsIteratorPrototype); iterator[context] = { target, kind, @@ -1155,12 +1164,12 @@ function createSearchParamsIterator(target, kind) { } // https://heycam.github.io/webidl/#dfn-iterator-prototype-object -const URLSearchParamsIteratorPrototype = Object.create(IteratorPrototype); +const URLSearchParamsIteratorPrototype = ObjectCreate(IteratorPrototype); defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', { next() { if (!this || - Object.getPrototypeOf(this) !== URLSearchParamsIteratorPrototype) { + ObjectGetPrototypeOf(this) !== URLSearchParamsIteratorPrototype) { throw new ERR_INVALID_THIS('URLSearchParamsIterator'); } @@ -1402,7 +1411,7 @@ function constructUrl(flags, protocol, username, password, ctx.fragment = fragment; ctx.host = host; - const url = Object.create(URL.prototype); + const url = ObjectCreate(URL.prototype); url[context] = ctx; const params = new URLSearchParams(); url[searchParams] = params; diff --git a/lib/internal/util.js b/lib/internal/util.js index dc2d7f1d2ff3f3..798e04e27c42a9 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -1,6 +1,15 @@ 'use strict'; -const { Object, Reflect } = primordials; +const { + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptor, + ObjectGetOwnPropertyDescriptors, + ObjectGetPrototypeOf, + ObjectSetPrototypeOf, + ReflectConstruct, +} = primordials; const { codes: { ERR_INVALID_ARG_TYPE, @@ -66,13 +75,13 @@ function deprecate(fn, msg, code) { } } if (new.target) { - return Reflect.construct(fn, args, new.target); + return ReflectConstruct(fn, args, new.target); } return fn.apply(this, args); } // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); + ObjectSetPrototypeOf(deprecated, fn); if (fn.prototype) { // Setting this (rather than using Object.setPrototype, as above) ensures // that calling the unwrapped constructor gives an instanceof the wrapped @@ -196,14 +205,14 @@ function cachedResult(fn) { // B() instanceof B // true function createClassWrapper(type) { function fn(...args) { - return Reflect.construct(type, args, new.target || type); + return ReflectConstruct(type, args, new.target || type); } // Mask the wrapper function name and length values - Object.defineProperties(fn, { + ObjectDefineProperties(fn, { name: { value: type.name }, length: { value: type.length } }); - Object.setPrototypeOf(fn, type); + ObjectSetPrototypeOf(fn, type); fn.prototype = type.prototype; return fn; } @@ -213,7 +222,7 @@ function getSignalsToNamesMapping() { if (signalsToNamesMapping !== undefined) return signalsToNamesMapping; - signalsToNamesMapping = Object.create(null); + signalsToNamesMapping = ObjectCreate(null); for (const key in signals) { signalsToNamesMapping[signals[key]] = key; } @@ -235,14 +244,14 @@ function convertToValidSignal(signal) { function getConstructorOf(obj) { while (obj) { - const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); + const descriptor = ObjectGetOwnPropertyDescriptor(obj, 'constructor'); if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '') { return descriptor.value; } - obj = Object.getPrototypeOf(obj); + obj = ObjectGetPrototypeOf(obj); } return null; @@ -265,7 +274,7 @@ function promisify(original) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('util.promisify.custom', 'Function', fn); } - return Object.defineProperty(fn, kCustomPromisifiedSymbol, { + return ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); } @@ -292,14 +301,14 @@ function promisify(original) { }); } - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + ObjectSetPrototypeOf(fn, ObjectGetPrototypeOf(original)); - Object.defineProperty(fn, kCustomPromisifiedSymbol, { + ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); - return Object.defineProperties( + return ObjectDefineProperties( fn, - Object.getOwnPropertyDescriptors(original) + ObjectGetOwnPropertyDescriptors(original) ); } diff --git a/lib/internal/util/comparisons.js b/lib/internal/util/comparisons.js index 52cd11429e6ac6..3af44f9bf53a51 100644 --- a/lib/internal/util/comparisons.js +++ b/lib/internal/util/comparisons.js @@ -1,19 +1,20 @@ 'use strict'; const { - BigIntPrototype, - BooleanPrototype, - DatePrototype, - Number, - NumberPrototype, - Object, - ObjectPrototype: { - hasOwnProperty, - propertyIsEnumerable, - toString: objectToString - }, - StringPrototype, - SymbolPrototype + BigIntPrototypeValueOf, + BooleanPrototypeValueOf, + DatePrototypeGetTime, + NumberIsNaN, + NumberPrototypeValueOf, + ObjectGetOwnPropertySymbols, + ObjectGetPrototypeOf, + ObjectIs, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ObjectPrototypePropertyIsEnumerable, + ObjectPrototypeToString, + StringPrototypeValueOf, + SymbolPrototypeValueOf, } = primordials; const { compare } = internalBinding('buffer'); @@ -83,24 +84,24 @@ function areEqualArrayBuffers(buf1, buf2) { function isEqualBoxedPrimitive(val1, val2) { if (isNumberObject(val1)) { return isNumberObject(val2) && - Object.is(NumberPrototype.valueOf(val1), - NumberPrototype.valueOf(val2)); + ObjectIs(NumberPrototypeValueOf(val1), + NumberPrototypeValueOf(val2)); } if (isStringObject(val1)) { return isStringObject(val2) && - StringPrototype.valueOf(val1) === StringPrototype.valueOf(val2); + StringPrototypeValueOf(val1) === StringPrototypeValueOf(val2); } if (isBooleanObject(val1)) { return isBooleanObject(val2) && - BooleanPrototype.valueOf(val1) === BooleanPrototype.valueOf(val2); + BooleanPrototypeValueOf(val1) === BooleanPrototypeValueOf(val2); } if (isBigIntObject(val1)) { return isBigIntObject(val2) && - BigIntPrototype.valueOf(val1) === BigIntPrototype.valueOf(val2); + BigIntPrototypeValueOf(val1) === BigIntPrototypeValueOf(val2); } if (isSymbolObject(val1)) { return isSymbolObject(val2) && - SymbolPrototype.valueOf(val1) === SymbolPrototype.valueOf(val2); + SymbolPrototypeValueOf(val1) === SymbolPrototypeValueOf(val2); } return false; } @@ -129,19 +130,19 @@ function innerDeepEqual(val1, val2, strict, memos) { if (val1 === val2) { if (val1 !== 0) return true; - return strict ? Object.is(val1, val2) : true; + return strict ? ObjectIs(val1, val2) : true; } // Check more closely if val1 and val2 are equal. if (strict) { if (typeof val1 !== 'object') { - return typeof val1 === 'number' && Number.isNaN(val1) && - Number.isNaN(val2); + return typeof val1 === 'number' && NumberIsNaN(val1) && + NumberIsNaN(val2); } if (typeof val2 !== 'object' || val1 === null || val2 === null) { return false; } - if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { + if (ObjectGetPrototypeOf(val1) !== ObjectGetPrototypeOf(val2)) { return false; } } else { @@ -156,8 +157,8 @@ function innerDeepEqual(val1, val2, strict, memos) { return false; } } - const val1Tag = objectToString(val1); - const val2Tag = objectToString(val2); + const val1Tag = ObjectPrototypeToString(val1); + const val2Tag = ObjectPrototypeToString(val2); if (val1Tag !== val2Tag) { return false; @@ -179,7 +180,7 @@ function innerDeepEqual(val1, val2, strict, memos) { return keyCheck(val1, val2, strict, memos, kNoIterator); } if (isDate(val1)) { - if (DatePrototype.getTime(val1) !== DatePrototype.getTime(val2)) { + if (DatePrototypeGetTime(val1) !== DatePrototypeGetTime(val2)) { return false; } } else if (isRegExp(val1)) { @@ -233,7 +234,7 @@ function innerDeepEqual(val1, val2, strict, memos) { } function getEnumerables(val, keys) { - return keys.filter((k) => propertyIsEnumerable(val, k)); + return keys.filter((k) => ObjectPrototypePropertyIsEnumerable(val, k)); } function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { @@ -245,8 +246,8 @@ function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { // d) For Sets and Maps, equal contents // Note: this accounts for both named and indexed properties on Arrays. if (arguments.length === 5) { - aKeys = Object.keys(val1); - const bKeys = Object.keys(val2); + aKeys = ObjectKeys(val1); + const bKeys = ObjectKeys(val2); // The pair must have the same number of owned properties. if (aKeys.length !== bKeys.length) { @@ -257,34 +258,34 @@ function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { // Cheap key test let i = 0; for (; i < aKeys.length; i++) { - if (!hasOwnProperty(val2, aKeys[i])) { + if (!ObjectPrototypeHasOwnProperty(val2, aKeys[i])) { return false; } } if (strict && arguments.length === 5) { - const symbolKeysA = Object.getOwnPropertySymbols(val1); + const symbolKeysA = ObjectGetOwnPropertySymbols(val1); if (symbolKeysA.length !== 0) { let count = 0; for (i = 0; i < symbolKeysA.length; i++) { const key = symbolKeysA[i]; - if (propertyIsEnumerable(val1, key)) { - if (!propertyIsEnumerable(val2, key)) { + if (ObjectPrototypePropertyIsEnumerable(val1, key)) { + if (!ObjectPrototypePropertyIsEnumerable(val2, key)) { return false; } aKeys.push(key); count++; - } else if (propertyIsEnumerable(val2, key)) { + } else if (ObjectPrototypePropertyIsEnumerable(val2, key)) { return false; } } - const symbolKeysB = Object.getOwnPropertySymbols(val2); + const symbolKeysB = ObjectGetOwnPropertySymbols(val2); if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { return false; } } else { - const symbolKeysB = Object.getOwnPropertySymbols(val2); + const symbolKeysB = ObjectGetOwnPropertySymbols(val2); if (symbolKeysB.length !== 0 && getEnumerables(val2, symbolKeysB).length !== 0) { return false; @@ -362,7 +363,7 @@ function findLooseMatchingPrimitives(prim) { // a regular number and not NaN. // Fall through case 'number': - if (Number.isNaN(prim)) { + if (NumberIsNaN(prim)) { return false; } } @@ -519,24 +520,24 @@ function objEquiv(a, b, strict, keys, memos, iterationType) { } } else if (iterationType === kIsArray) { for (; i < a.length; i++) { - if (hasOwnProperty(a, i)) { - if (!hasOwnProperty(b, i) || + if (ObjectPrototypeHasOwnProperty(a, i)) { + if (!ObjectPrototypeHasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { return false; } - } else if (hasOwnProperty(b, i)) { + } else if (ObjectPrototypeHasOwnProperty(b, i)) { return false; } else { // Array is sparse. - const keysA = Object.keys(a); + const keysA = ObjectKeys(a); for (; i < keysA.length; i++) { const key = keysA[i]; - if (!hasOwnProperty(b, key) || + if (!ObjectPrototypeHasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } - if (keysA.length !== Object.keys(b).length) { + if (keysA.length !== ObjectKeys(b).length) { return false; } return true; diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index d16ecf7412f2e7..c065d1dc6e3f8a 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1,23 +1,42 @@ 'use strict'; const { - BigIntPrototype, - BooleanPrototype, - DatePrototype, - ErrorPrototype, - JSON, - MapPrototype, - Math, - NumberPrototype, - Object, - ObjectPrototype: { - hasOwnProperty, - propertyIsEnumerable - }, - RegExpPrototype, - SetPrototype, - StringPrototype, - SymbolPrototype, + ArrayIsArray, + BigIntPrototypeValueOf, + BooleanPrototypeValueOf, + DatePrototypeGetTime, + DatePrototypeToISOString, + DatePrototypeToString, + ErrorPrototypeToString, + JSONStringify, + MapPrototypeEntries, + MathFloor, + MathMax, + MathMin, + MathRound, + MathSqrt, + NumberPrototypeValueOf, + ObjectAssign, + ObjectCreate, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptor, + ObjectGetOwnPropertyDescriptors, + ObjectGetOwnPropertyNames, + ObjectGetOwnPropertySymbols, + ObjectGetPrototypeOf, + ObjectIs, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ObjectPrototypePropertyIsEnumerable, + ObjectSeal, + RegExpPrototypeToString, + SetPrototypeValues, + StringPrototypeValueOf, + SymbolPrototypeToString, + SymbolPrototypeValueOf, + SymbolIterator, + SymbolToStringTag, uncurryThis } = primordials; @@ -94,10 +113,10 @@ const { NativeModule } = require('internal/bootstrap/loaders'); let hexSlice; const builtInObjects = new Set( - Object.getOwnPropertyNames(global).filter((e) => /^([A-Z][a-z]+)+$/.test(e)) + ObjectGetOwnPropertyNames(global).filter((e) => /^([A-Z][a-z]+)+$/.test(e)) ); -const inspectDefaultOptions = Object.seal({ +const inspectDefaultOptions = ObjectSeal({ showHidden: false, depth: 2, colors: false, @@ -153,7 +172,7 @@ const meta = [ function getUserOptions(ctx) { const obj = { stylize: ctx.stylize }; - for (const key of Object.keys(inspectDefaultOptions)) { + for (const key of ObjectKeys(inspectDefaultOptions)) { obj[key] = ctx[key]; } if (ctx.userOptions === undefined) @@ -202,12 +221,14 @@ function inspect(value, opts) { if (typeof opts === 'boolean') { ctx.showHidden = opts; } else if (opts) { - const optKeys = Object.keys(opts); + const optKeys = ObjectKeys(opts); for (const key of optKeys) { // TODO(BridgeAR): Find a solution what to do about stylize. Either make // this function public or add a new API with a similar or better // functionality. - if (hasOwnProperty(inspectDefaultOptions, key) || key === 'stylize') { + if ( + ObjectPrototypeHasOwnProperty(inspectDefaultOptions, key) || + key === 'stylize') { ctx[key] = opts[key]; } else if (ctx.userOptions === undefined) { // This is required to pass through the actual user input. @@ -222,7 +243,7 @@ function inspect(value, opts) { } inspect.custom = customInspectSymbol; -Object.defineProperty(inspect, 'defaultOptions', { +ObjectDefineProperty(inspect, 'defaultOptions', { get() { return inspectDefaultOptions; }, @@ -230,12 +251,12 @@ Object.defineProperty(inspect, 'defaultOptions', { if (options === null || typeof options !== 'object') { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } - return Object.assign(inspectDefaultOptions, options); + return ObjectAssign(inspectDefaultOptions, options); } }); // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = Object.assign(Object.create(null), { +inspect.colors = ObjectAssign(ObjectCreate(null), { bold: [1, 22], italic: [3, 23], underline: [4, 24], @@ -252,7 +273,7 @@ inspect.colors = Object.assign(Object.create(null), { }); // Don't use 'blue' not visible on cmd.exe -inspect.styles = Object.assign(Object.create(null), { +inspect.styles = ObjectAssign(ObjectCreate(null), { special: 'cyan', number: 'yellow', bigint: 'yellow', @@ -355,14 +376,14 @@ function getConstructorName(obj, ctx, recurseTimes) { let firstProto; const tmp = obj; while (obj) { - const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); + const descriptor = ObjectGetOwnPropertyDescriptor(obj, 'constructor'); if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '') { return descriptor.value.name; } - obj = Object.getPrototypeOf(obj); + obj = ObjectGetPrototypeOf(obj); if (firstProto === undefined) { firstProto = obj; } @@ -408,9 +429,9 @@ function getPrefix(constructor, tag, fallback) { // Look up the keys of the object. function getKeys(value, showHidden) { let keys; - const symbols = Object.getOwnPropertySymbols(value); + const symbols = ObjectGetOwnPropertySymbols(value); if (showHidden) { - keys = Object.getOwnPropertyNames(value); + keys = ObjectGetOwnPropertyNames(value); if (symbols.length !== 0) keys.push(...symbols); } else { @@ -420,14 +441,15 @@ function getKeys(value, showHidden) { // TODO(devsnek): track https://github.com/tc39/ecma262/issues/1209 // and modify this logic as needed. try { - keys = Object.keys(value); + keys = ObjectKeys(value); } catch (err) { assert(isNativeError(err) && err.name === 'ReferenceError' && isModuleNamespaceObject(value)); - keys = Object.getOwnPropertyNames(value); + keys = ObjectGetOwnPropertyNames(value); } if (symbols.length !== 0) { - keys.push(...symbols.filter((key) => propertyIsEnumerable(value, key))); + const filter = (key) => ObjectPrototypePropertyIsEnumerable(value, key); + keys.push(...symbols.filter(filter)); } } return keys; @@ -492,12 +514,12 @@ function clazzWithNullPrototype(clazz, name) { } } class NullPrototype extends clazz { - get [Symbol.toStringTag]() { + get [SymbolToStringTag]() { return ''; } } - Object.defineProperty(NullPrototype.prototype.constructor, 'name', - { value: `[${name}: null prototype]` }); + ObjectDefineProperty(NullPrototype.prototype.constructor, 'name', + { value: `[${name}: null prototype]` }); lazyNullPrototypeCache.set(clazz, NullPrototype); return NullPrototype; } @@ -506,11 +528,11 @@ function noPrototypeIterator(ctx, value, recurseTimes) { let newVal; if (isSet(value)) { const clazz = clazzWithNullPrototype(Set, 'Set'); - newVal = new clazz(SetPrototype.values(value)); + newVal = new clazz(SetPrototypeValues(value)); } else if (isMap(value)) { const clazz = clazzWithNullPrototype(Map, 'Map'); - newVal = new clazz(MapPrototype.entries(value)); - } else if (Array.isArray(value)) { + newVal = new clazz(MapPrototypeEntries(value)); + } else if (ArrayIsArray(value)) { const clazz = clazzWithNullPrototype(Array, 'Array'); newVal = new clazz(value.length); } else if (isTypedArray(value)) { @@ -519,7 +541,7 @@ function noPrototypeIterator(ctx, value, recurseTimes) { newVal = new clazz(value); } if (newVal !== undefined) { - Object.defineProperties(newVal, Object.getOwnPropertyDescriptors(value)); + ObjectDefineProperties(newVal, ObjectGetOwnPropertyDescriptors(value)); return formatRaw(ctx, newVal, recurseTimes); } } @@ -595,13 +617,15 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { let keys; const constructor = getConstructorName(value, ctx, recurseTimes); - let tag = value[Symbol.toStringTag]; + let tag = value[SymbolToStringTag]; // Only list the tag in case it's non-enumerable / not an own property. // Otherwise we'd print this twice. if (typeof tag !== 'string' || (tag !== '' && - (ctx.showHidden ? hasOwnProperty : propertyIsEnumerable)( - value, Symbol.toStringTag + (ctx.showHidden ? + ObjectPrototypeHasOwnProperty : + ObjectPrototypePropertyIsEnumerable)( + value, SymbolToStringTag ))) { tag = ''; } @@ -615,9 +639,9 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { let extrasType = kObjectType; // Iterators and the rest are split to reduce checks. - if (value[Symbol.iterator]) { + if (value[SymbolIterator]) { noIterator = false; - if (Array.isArray(value)) { + if (ArrayIsArray(value)) { keys = getOwnNonIndexProperties(value, filter); // Only set the constructor for non ordinary ("Array [...]") arrays. const prefix = getPrefix(constructor, tag, 'Array'); @@ -680,7 +704,7 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { return ctx.stylize(base, 'special'); } else if (isRegExp(value)) { // Make RegExps say that they are RegExps - base = RegExpPrototype.toString( + base = RegExpPrototypeToString( constructor !== null ? value : new RegExp(value) ); const prefix = getPrefix(constructor, tag, 'RegExp'); @@ -690,9 +714,9 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { return ctx.stylize(base, 'regexp'); } else if (isDate(value)) { // Make dates with properties first say the date - base = Number.isNaN(DatePrototype.getTime(value)) ? - DatePrototype.toString(value) : - DatePrototype.toISOString(value); + base = Number.isNaN(DatePrototypeGetTime(value)) ? + DatePrototypeToString(value) : + DatePrototypeToISOString(value); const prefix = getPrefix(constructor, tag, 'Date'); if (prefix !== 'Date ') base = `${prefix}${base}`; @@ -842,23 +866,23 @@ function getBoxedBase(value, ctx, keys, constructor, tag) { let fn; let type; if (isNumberObject(value)) { - fn = NumberPrototype; + fn = NumberPrototypeValueOf; type = 'Number'; } else if (isStringObject(value)) { - fn = StringPrototype; + fn = StringPrototypeValueOf; type = 'String'; // For boxed Strings, we have to remove the 0-n indexed entries, // since they just noisy up the output and are redundant // Make boxed primitive Strings look like such keys.splice(0, value.length); } else if (isBooleanObject(value)) { - fn = BooleanPrototype; + fn = BooleanPrototypeValueOf; type = 'Boolean'; } else if (isBigIntObject(value)) { - fn = BigIntPrototype; + fn = BigIntPrototypeValueOf; type = 'BigInt'; } else { - fn = SymbolPrototype; + fn = SymbolPrototypeValueOf; type = 'Symbol'; } let base = `[${type}`; @@ -869,7 +893,7 @@ function getBoxedBase(value, ctx, keys, constructor, tag) { base += ` (${constructor})`; } } - base += `: ${formatPrimitive(stylizeNoColor, fn.valueOf(value), ctx)}]`; + base += `: ${formatPrimitive(stylizeNoColor, fn(value), ctx)}]`; if (tag !== '' && tag !== constructor) { base += ` [${tag}]`; } @@ -906,7 +930,7 @@ function getFunctionBase(value, constructor, tag) { function formatError(err, constructor, tag, ctx) { const name = err.name != null ? String(err.name) : 'Error'; let len = name.length; - let stack = err.stack ? String(err.stack) : ErrorPrototype.toString(err); + let stack = err.stack ? String(err.stack) : ErrorPrototypeToString(err); // A stack trace may contain arbitrary data. Only manipulate the output // for "regular errors" (errors that "look normal") for now. @@ -1007,22 +1031,22 @@ function groupArrayElements(ctx, output, value) { (totalLength / actualMax > 5 || maxLength <= 6)) { const approxCharHeights = 2.5; - const averageBias = Math.sqrt(actualMax - totalLength / output.length); - const biasedMax = Math.max(actualMax - 3 - averageBias, 1); + const averageBias = MathSqrt(actualMax - totalLength / output.length); + const biasedMax = MathMax(actualMax - 3 - averageBias, 1); // Dynamically check how many columns seem possible. - const columns = Math.min( + const columns = MathMin( // Ideally a square should be drawn. We expect a character to be about 2.5 // times as high as wide. This is the area formula to calculate a square // which contains n rectangles of size `actualMax * approxCharHeights`. // Divide that by `actualMax` to receive the correct number of columns. // The added bias increases the columns for short entries. - Math.round( - Math.sqrt( + MathRound( + MathSqrt( approxCharHeights * biasedMax * outputLength ) / biasedMax ), // Do not exceed the breakLength. - Math.floor((ctx.breakLength - ctx.indentationLvl) / actualMax), + MathFloor((ctx.breakLength - ctx.indentationLvl) / actualMax), // Limit array grouping for small `compact` modes as the user requested // minimal grouping. ctx.compact * 4, @@ -1056,7 +1080,7 @@ function groupArrayElements(ctx, output, value) { // Each iteration creates a single line of grouped entries. for (let i = 0; i < outputLength; i += columns) { // The last lines may contain less entries than columns. - const max = Math.min(i + columns, outputLength); + const max = MathMin(i + columns, outputLength); let str = ''; let j = i; for (; j < max - 1; j++) { @@ -1100,7 +1124,7 @@ function handleMaxCallStackSize(ctx, err, constructorName, indentationLvl) { function formatNumber(fn, value) { // Format -0 as '-0'. Checking `value === -0` won't distinguish 0 from -0. - return fn(Object.is(value, -0) ? '-0' : `${value}`, 'number'); + return fn(ObjectIs(value, -0) ? '-0' : `${value}`, 'number'); } function formatBigInt(fn, value) { @@ -1128,7 +1152,7 @@ function formatPrimitive(fn, value, ctx) { if (typeof value === 'undefined') return fn('undefined', 'undefined'); // es6 symbol primitive - return fn(SymbolPrototype.toString(value), 'symbol'); + return fn(SymbolPrototypeToString(value), 'symbol'); } function formatNamespaceObject(ctx, value, recurseTimes, keys) { @@ -1160,7 +1184,7 @@ function formatNamespaceObject(ctx, value, recurseTimes, keys) { // The array is sparse and/or has extra keys function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) { - const keys = Object.keys(value); + const keys = ObjectKeys(value); let index = i; for (; i < keys.length && output.length < maxLength; i++) { const key = keys[i]; @@ -1207,7 +1231,7 @@ function formatArrayBuffer(ctx, value) { } if (hexSlice === undefined) hexSlice = uncurryThis(require('buffer').Buffer.prototype.hexSlice); - let str = hexSlice(buffer, 0, Math.min(ctx.maxArrayLength, buffer.length)) + let str = hexSlice(buffer, 0, MathMin(ctx.maxArrayLength, buffer.length)) .replace(/(.{2})/g, '$1 ').trim(); const remaining = buffer.length - ctx.maxArrayLength; if (remaining > 0) @@ -1217,13 +1241,13 @@ function formatArrayBuffer(ctx, value) { function formatArray(ctx, value, recurseTimes) { const valLen = value.length; - const len = Math.min(Math.max(0, ctx.maxArrayLength), valLen); + const len = MathMin(MathMax(0, ctx.maxArrayLength), valLen); const remaining = valLen - len; const output = []; for (let i = 0; i < len; i++) { // Special handle sparse arrays. - if (!hasOwnProperty(value, i)) { + if (!ObjectPrototypeHasOwnProperty(value, i)) { return formatSpecialArray(ctx, value, recurseTimes, len, output, i); } output.push(formatProperty(ctx, value, recurseTimes, i, kArrayType)); @@ -1234,7 +1258,7 @@ function formatArray(ctx, value, recurseTimes) { } function formatTypedArray(ctx, value, recurseTimes) { - const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length); + const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), value.length); const remaining = value.length - maxLength; const output = new Array(maxLength); const elementFormatter = value.length > 0 && typeof value[0] === 'number' ? @@ -1272,7 +1296,7 @@ function formatSet(ctx, value, recurseTimes) { ctx.indentationLvl -= 2; // With `showHidden`, `length` will display as a hidden property for // arrays. For consistency's sake, do the same for `size`, even though this - // property isn't selected by Object.getOwnPropertyNames(). + // property isn't selected by ObjectGetOwnPropertyNames(). if (ctx.showHidden) output.push(`[size]: ${ctx.stylize(`${value.size}`, 'number')}`); return output; @@ -1293,8 +1317,8 @@ function formatMap(ctx, value, recurseTimes) { } function formatSetIterInner(ctx, recurseTimes, entries, state) { - const maxArrayLength = Math.max(ctx.maxArrayLength, 0); - const maxLength = Math.min(maxArrayLength, entries.length); + const maxArrayLength = MathMax(ctx.maxArrayLength, 0); + const maxLength = MathMin(maxArrayLength, entries.length); let output = new Array(maxLength); ctx.indentationLvl += 2; for (let i = 0; i < maxLength; i++) { @@ -1315,11 +1339,11 @@ function formatSetIterInner(ctx, recurseTimes, entries, state) { } function formatMapIterInner(ctx, recurseTimes, entries, state) { - const maxArrayLength = Math.max(ctx.maxArrayLength, 0); + const maxArrayLength = MathMax(ctx.maxArrayLength, 0); // Entries exist as [key1, val1, key2, val2, ...] const len = entries.length / 2; const remaining = len - maxArrayLength; - const maxLength = Math.min(maxArrayLength, len); + const maxLength = MathMin(maxArrayLength, len); let output = new Array(maxLength); let i = 0; ctx.indentationLvl += 2; @@ -1398,7 +1422,7 @@ function formatPromise(ctx, value, recurseTimes) { function formatProperty(ctx, value, recurseTimes, key, type) { let name, str; let extra = ' '; - const desc = Object.getOwnPropertyDescriptor(value, key) || + const desc = ObjectGetOwnPropertyDescriptor(value, key) || { value: value[key], enumerable: true }; if (desc.value !== undefined) { const diff = (type !== kObjectType || ctx.compact !== true) ? 2 : 3; @@ -1548,12 +1572,12 @@ const firstErrorLine = (error) => error.message.split('\n')[0]; let CIRCULAR_ERROR_MESSAGE; function tryStringify(arg) { try { - return JSON.stringify(arg); + return JSONStringify(arg); } catch (err) { // Populate the circular error message lazily if (!CIRCULAR_ERROR_MESSAGE) { try { - const a = {}; a.a = a; JSON.stringify(a); + const a = {}; a.a = a; JSONStringify(a); } catch (err) { CIRCULAR_ERROR_MESSAGE = firstErrorLine(err); } @@ -1596,13 +1620,14 @@ function formatWithOptions(inspectOptions, ...args) { tempArg === null || (typeof tempArg.toString === 'function' && // A direct own property. - (hasOwnProperty(tempArg, 'toString') || + (ObjectPrototypeHasOwnProperty(tempArg, 'toString') || // A direct own property on the constructor prototype in // case the constructor is not an built-in object. ((constr = tempArg.constructor) && !builtInObjects.has(constr.name) && constr.prototype && - hasOwnProperty(constr.prototype, 'toString'))))) { + ObjectPrototypeHasOwnProperty(constr.prototype, + 'toString'))))) { tempStr = String(tempArg); } else { tempStr = inspect(tempArg, { diff --git a/lib/internal/util/inspector.js b/lib/internal/util/inspector.js index 5230137fce6ef9..5f11eff21a2a15 100644 --- a/lib/internal/util/inspector.js +++ b/lib/internal/util/inspector.js @@ -1,6 +1,8 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectKeys, +} = primordials; let session; function sendInspectorCommand(cb, onError) { @@ -36,7 +38,7 @@ function installConsoleExtensions(commandLineApi) { // Wrap a console implemented by Node.js with features from the VM inspector function wrapConsole(consoleFromNode, consoleFromVM) { const { consoleCall } = internalBinding('inspector'); - for (const key of Object.keys(consoleFromVM)) { + for (const key of ObjectKeys(consoleFromVM)) { // If global console has the same method as inspector console, // then wrap these two methods into one. Native wrapper will preserve // the original stack. diff --git a/lib/internal/util/types.js b/lib/internal/util/types.js index 3f05ad06ac53be..676f386a2458d4 100644 --- a/lib/internal/util/types.js +++ b/lib/internal/util/types.js @@ -1,16 +1,19 @@ 'use strict'; -const { Object, uncurryThis } = primordials; +const { + ArrayBufferIsView, + ObjectGetOwnPropertyDescriptor, + ObjectGetPrototypeOf, + SymbolToStringTag, + uncurryThis, +} = primordials; -const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype); +const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8Array.prototype); const TypedArrayProto_toStringTag = uncurryThis( - Object.getOwnPropertyDescriptor(TypedArrayPrototype, - Symbol.toStringTag).get); - -// Cached to make sure no userland code can tamper with it. -const isArrayBufferView = ArrayBuffer.isView; + ObjectGetOwnPropertyDescriptor(TypedArrayPrototype, + SymbolToStringTag).get); function isTypedArray(value) { return TypedArrayProto_toStringTag(value) !== undefined; @@ -62,7 +65,7 @@ function isBigUint64Array(value) { module.exports = { ...internalBinding('types'), - isArrayBufferView, + isArrayBufferView: ArrayBufferIsView, isTypedArray, isUint8Array, isUint8ClampedArray, diff --git a/lib/internal/v8_prof_processor.js b/lib/internal/v8_prof_processor.js index 7a942d3225a2a9..d647d4749f9adc 100644 --- a/lib/internal/v8_prof_processor.js +++ b/lib/internal/v8_prof_processor.js @@ -1,6 +1,8 @@ 'use strict'; -const { JSON } = primordials; +const { + JSONStringify, +} = primordials; const vm = require('vm'); @@ -32,7 +34,7 @@ if (process.platform === 'darwin') { } tickArguments.push.apply(tickArguments, process.argv.slice(1)); script = `(function(module, require) { - arguments = ${JSON.stringify(tickArguments)}; + arguments = ${JSONStringify(tickArguments)}; function write (s) { process.stdout.write(s) } function printErr(err) { console.error(err); } ${script} diff --git a/lib/internal/vm/module.js b/lib/internal/vm/module.js index 169313c8dda8cc..c97556ceb843d7 100644 --- a/lib/internal/vm/module.js +++ b/lib/internal/vm/module.js @@ -1,6 +1,11 @@ 'use strict'; -const { Object, Symbol, SafePromise } = primordials; +const { + ObjectCreate, + ObjectDefineProperty, + Symbol, + SafePromise, +} = primordials; const { isContext } = internalBinding('contextify'); const { isModuleNamespaceObject } = require('internal/util/types'); @@ -89,7 +94,7 @@ class Module { context[kPerContextModuleId] += 1; } else { identifier = `${defaultModuleName}(0)`; - Object.defineProperty(context, kPerContextModuleId, { + ObjectDefineProperty(context, kPerContextModuleId, { value: 1, writable: true, enumerable: false, @@ -217,7 +222,7 @@ class Module { if (typeof depth === 'number' && depth < 0) return options.stylize(`[${ctor.name}]`, 'special'); - const o = Object.create({ constructor: ctor }); + const o = ObjectCreate({ constructor: ctor }); o.status = this.status; o.identifier = this.identifier; o.context = this.context; diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 614f93010515b3..699bf24346db91 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -2,7 +2,11 @@ /* global SharedArrayBuffer */ -const { Math, Object } = primordials; +const { + MathMax, + ObjectCreate, + ObjectEntries, +} = primordials; const EventEmitter = require('events'); const assert = require('internal/assert'); @@ -94,8 +98,8 @@ class Worker extends EventEmitter { let env; if (typeof options.env === 'object' && options.env !== null) { - env = Object.create(null); - for (const [ key, value ] of Object.entries(options.env)) + env = ObjectCreate(null); + for (const [ key, value ] of ObjectEntries(options.env)) env[key] = `${value}`; } else if (options.env == null) { env = process.env; @@ -318,7 +322,7 @@ function parseResourceLimits(obj) { if (typeof obj !== 'object' || obj === null) return ret; if (typeof obj.maxOldGenerationSizeMb === 'number') - ret[kMaxOldGenerationSizeMb] = Math.max(obj.maxOldGenerationSizeMb, 2); + ret[kMaxOldGenerationSizeMb] = MathMax(obj.maxOldGenerationSizeMb, 2); if (typeof obj.maxYoungGenerationSizeMb === 'number') ret[kMaxYoungGenerationSizeMb] = obj.maxYoungGenerationSizeMb; if (typeof obj.codeRangeSizeMb === 'number') diff --git a/lib/internal/worker/io.js b/lib/internal/worker/io.js index ba2150e530b5be..a672dac94ce7e5 100644 --- a/lib/internal/worker/io.js +++ b/lib/internal/worker/io.js @@ -1,6 +1,13 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectAssign, + ObjectCreate, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptors, + ObjectGetPrototypeOf, + ObjectSetPrototypeOf, +} = primordials; const { handle_onclose: handleOnCloseSymbol, @@ -48,12 +55,12 @@ const messageTypes = { // not provide methods that are not present in the Browser and not documented // on our side (e.g. hasRef). // Save a copy of the original set of methods as a shallow clone. -const MessagePortPrototype = Object.create( - Object.getPrototypeOf(MessagePort.prototype), - Object.getOwnPropertyDescriptors(MessagePort.prototype)); +const MessagePortPrototype = ObjectCreate( + ObjectGetPrototypeOf(MessagePort.prototype), + ObjectGetOwnPropertyDescriptors(MessagePort.prototype)); // Set up the new inheritance chain. -Object.setPrototypeOf(MessagePort, EventEmitter); -Object.setPrototypeOf(MessagePort.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(MessagePort, EventEmitter); +ObjectSetPrototypeOf(MessagePort.prototype, EventEmitter.prototype); // Copy methods that are inherited from HandleWrap, because // changing the prototype of MessagePort.prototype implicitly removed them. MessagePort.prototype.ref = MessagePortPrototype.ref; @@ -73,7 +80,7 @@ MessagePort.prototype[kOnMessageListener] = function onmessage(event) { // This is for compatibility with the Web's MessagePort API. It makes sense to // provide it as an `EventEmitter` in Node.js, but if somebody overrides // `onmessage`, we'll switch over to the Web API model. -Object.defineProperty(MessagePort.prototype, 'onmessage', { +ObjectDefineProperty(MessagePort.prototype, 'onmessage', { enumerable: true, configurable: true, get() { @@ -96,7 +103,7 @@ function oninit() { setupPortReferencing(this, this, 'message'); } -Object.defineProperty(MessagePort.prototype, onInitSymbol, { +ObjectDefineProperty(MessagePort.prototype, onInitSymbol, { enumerable: true, writable: false, value: oninit @@ -107,7 +114,7 @@ function onclose() { this.emit('close'); } -Object.defineProperty(MessagePort.prototype, handleOnCloseSymbol, { +ObjectDefineProperty(MessagePort.prototype, handleOnCloseSymbol, { enumerable: false, writable: false, value: onclose @@ -119,7 +126,7 @@ MessagePort.prototype.close = function(cb) { MessagePortPrototype.close.call(this); }; -Object.defineProperty(MessagePort.prototype, inspect.custom, { +ObjectDefineProperty(MessagePort.prototype, inspect.custom, { enumerable: false, writable: false, value: function inspect() { // eslint-disable-line func-name-matching @@ -129,14 +136,14 @@ Object.defineProperty(MessagePort.prototype, inspect.custom, { // e.g. when accessing the prototype directly. ref = MessagePortPrototype.hasRef.call(this); } catch { return this; } - return Object.assign(Object.create(MessagePort.prototype), - ref === undefined ? { - active: false, - } : { - active: true, - refed: ref - }, - this); + return ObjectAssign(ObjectCreate(MessagePort.prototype), + ref === undefined ? { + active: false, + } : { + active: true, + refed: ref + }, + this); } }); diff --git a/lib/net.js b/lib/net.js index 2ff9bbd216fcfa..749895444b237a 100644 --- a/lib/net.js +++ b/lib/net.js @@ -22,10 +22,8 @@ 'use strict'; const { - Object: { - defineProperty: ObjectDefineProperty, - setPrototypeOf: ObjectSetPrototypeOf - } + ObjectDefineProperty, + ObjectSetPrototypeOf, } = primordials; const EventEmitter = require('events'); diff --git a/lib/os.js b/lib/os.js index d312c7d298e3ec..51520802d8ecf7 100644 --- a/lib/os.js +++ b/lib/os.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperties, +} = primordials; const { safeGetenv } = internalBinding('credentials'); const constants = internalBinding('constants').os; @@ -287,7 +289,7 @@ module.exports = { tmpDir: deprecate(tmpdir, tmpDirDeprecationMsg, 'DEP0022') }; -Object.defineProperties(module.exports, { +ObjectDefineProperties(module.exports, { constants: { configurable: false, enumerable: true, diff --git a/lib/perf_hooks.js b/lib/perf_hooks.js index dbaf2a39fe6d19..36bff74446e302 100644 --- a/lib/perf_hooks.js +++ b/lib/perf_hooks.js @@ -1,6 +1,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperties, + ObjectDefineProperty, + ObjectKeys, +} = primordials; const { ELDHistogram: _ELDHistogram, @@ -215,7 +219,7 @@ const nodeTiming = new PerformanceNodeTiming(); // Maintains a list of entries as a linked list stored in insertion order. class PerformanceObserverEntryList { constructor() { - Object.defineProperties(this, { + ObjectDefineProperties(this, { [kEntries]: { writable: true, enumerable: false, @@ -280,7 +284,7 @@ class PerformanceObserver extends AsyncResource { throw new ERR_INVALID_CALLBACK(callback); } super('PerformanceObserver'); - Object.defineProperties(this, { + ObjectDefineProperties(this, { [kTypes]: { enumerable: false, writable: true, @@ -312,7 +316,7 @@ class PerformanceObserver extends AsyncResource { disconnect() { const observerCountsGC = observerCounts[NODE_PERFORMANCE_ENTRY_TYPE_GC]; const types = this[kTypes]; - const keys = Object.keys(types); + const keys = ObjectKeys(types); for (var n = 0; n < keys.length; n++) { const item = types[keys[n]]; if (item) { @@ -413,13 +417,13 @@ class Performance { if (fn[kTimerified]) return fn[kTimerified]; const ret = timerify(fn, fn.length); - Object.defineProperty(fn, kTimerified, { + ObjectDefineProperty(fn, kTimerified, { enumerable: false, configurable: true, writable: false, value: ret }); - Object.defineProperties(ret, { + ObjectDefineProperties(ret, { [kTimerified]: { enumerable: false, configurable: true, @@ -613,7 +617,7 @@ module.exports = { monitorEventLoopDelay }; -Object.defineProperty(module.exports, 'constants', { +ObjectDefineProperty(module.exports, 'constants', { configurable: false, enumerable: true, value: constants diff --git a/lib/querystring.js b/lib/querystring.js index 40f6d3dafb2b56..1573114e08194d 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -23,7 +23,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectCreate, + ObjectKeys, +} = primordials; const { Buffer } = require('buffer'); const { @@ -167,7 +170,7 @@ function stringify(obj, sep, eq, options) { } if (obj !== null && typeof obj === 'object') { - const keys = Object.keys(obj); + const keys = ObjectKeys(obj); const len = keys.length; const flast = len - 1; let fields = ''; @@ -233,7 +236,7 @@ function addKeyVal(obj, key, value, keyEncoded, valEncoded, decode) { // Parse a key/val string. function parse(qs, sep, eq, options) { - const obj = Object.create(null); + const obj = ObjectCreate(null); if (typeof qs !== 'string' || qs.length === 0) { return obj; diff --git a/lib/readline.js b/lib/readline.js index 95402020f07d71..e9a0c9d305a3e3 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -27,7 +27,13 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathCeil, + MathFloor, + MathMax, + ObjectDefineProperty, + ObjectSetPrototypeOf, +} = primordials; const { ERR_INVALID_CALLBACK, @@ -146,7 +152,7 @@ function Interface(input, output, completer, terminal) { this.historySize = historySize; this.removeHistoryDuplicates = !!removeHistoryDuplicates; this.crlfDelay = crlfDelay ? - Math.max(kMincrlfDelay, crlfDelay) : kMincrlfDelay; + MathMax(kMincrlfDelay, crlfDelay) : kMincrlfDelay; // Check arity, 2 - for async, 1 for sync if (typeof completer === 'function') { this.completer = completer.length === 2 ? @@ -247,10 +253,10 @@ function Interface(input, output, completer, terminal) { input.resume(); } -Object.setPrototypeOf(Interface.prototype, EventEmitter.prototype); -Object.setPrototypeOf(Interface, EventEmitter); +ObjectSetPrototypeOf(Interface.prototype, EventEmitter.prototype); +ObjectSetPrototypeOf(Interface, EventEmitter); -Object.defineProperty(Interface.prototype, 'columns', { +ObjectDefineProperty(Interface.prototype, 'columns', { configurable: true, enumerable: true, get: function() { @@ -503,7 +509,7 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) { const width = completions.reduce(function completionReducer(a, b) { return a.length > b.length ? a : b; }).length + 2; // 2 space padding - let maxColumns = Math.floor(self.columns / width); + let maxColumns = MathFloor(self.columns / width); if (!maxColumns || maxColumns === Infinity) { maxColumns = 1; } @@ -537,7 +543,7 @@ function handleGroup(self, group, width, maxColumns) { if (group.length === 0) { return; } - const minRows = Math.ceil(group.length / maxColumns); + const minRows = MathCeil(group.length / maxColumns); for (let row = 0; row < minRows; row++) { for (let col = 0; col < maxColumns; col++) { const idx = row * maxColumns + col; @@ -729,7 +735,7 @@ Interface.prototype._getDisplayPos = function(str) { } if (code === 0x0a) { // new line \n // row must be incremented by 1 even if offset = 0 or col = +Infinity - row += Math.ceil(offset / col) || 1; + row += MathCeil(offset / col) || 1; offset = 0; continue; } diff --git a/lib/repl.js b/lib/repl.js index c325a2e9fbe87f..fe88192642e675 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -42,7 +42,18 @@ 'use strict'; -const { Math, Object, ObjectPrototype } = primordials; +const { + MathMax, + ObjectAssign, + ObjectCreate, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptor, + ObjectGetOwnPropertyNames, + ObjectGetPrototypeOf, + ObjectKeys, + ObjectPrototypeHasOwnProperty, + ObjectSetPrototypeOf, +} = primordials; const { builtinLibs, @@ -236,7 +247,7 @@ function REPLServer(prompt, domainSet.add(this._domain); let rli = this; - Object.defineProperty(this, 'rli', { + ObjectDefineProperty(this, 'rli', { get: deprecate(() => rli, 'REPLServer.rli is deprecated', 'DEP0124'), set: deprecate((val) => rli = val, @@ -560,7 +571,7 @@ function REPLServer(prompt, self.lines.level = []; self.clearBufferedCommand(); - Object.defineProperty(this, 'bufferedCommand', { + ObjectDefineProperty(this, 'bufferedCommand', { get: deprecate(() => self[kBufferedCommandSymbol], 'REPLServer.bufferedCommand is deprecated', 'DEP0074'), @@ -588,7 +599,7 @@ function REPLServer(prompt, prompt }); - this.commands = Object.create(null); + this.commands = ObjectCreate(null); defineDefaultCommands(this); // Figure out which "writer" function to use @@ -599,7 +610,7 @@ function REPLServer(prompt, writer.options.colors = self.useColors; if (options[kStandaloneREPL]) { - Object.defineProperty(inspect, 'replDefaults', { + ObjectDefineProperty(inspect, 'replDefaults', { get() { return writer.options; }, @@ -607,7 +618,7 @@ function REPLServer(prompt, if (options === null || typeof options !== 'object') { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } - return Object.assign(writer.options, options); + return ObjectAssign(writer.options, options); }, enumerable: true, configurable: true @@ -828,8 +839,8 @@ function REPLServer(prompt, self.displayPrompt(); } -Object.setPrototypeOf(REPLServer.prototype, Interface.prototype); -Object.setPrototypeOf(REPLServer, Interface); +ObjectSetPrototypeOf(REPLServer.prototype, Interface.prototype); +ObjectSetPrototypeOf(REPLServer, Interface); exports.REPLServer = REPLServer; @@ -892,16 +903,16 @@ REPLServer.prototype.createContext = function() { }, () => { context = vm.createContext(); }); - for (const name of Object.getOwnPropertyNames(global)) { + for (const name of ObjectGetOwnPropertyNames(global)) { // Only set properties on the context that do not exist as primordial. if (!(name in primordials)) { - Object.defineProperty(context, name, - Object.getOwnPropertyDescriptor(global, name)); + ObjectDefineProperty(context, name, + ObjectGetOwnPropertyDescriptor(global, name)); } } context.global = context; const _console = new Console(this.outputStream); - Object.defineProperty(context, 'console', { + ObjectDefineProperty(context, 'console', { configurable: true, writable: true, value: _console @@ -911,12 +922,12 @@ REPLServer.prototype.createContext = function() { const module = new CJSModule(''); module.paths = CJSModule._resolveLookupPaths('', parentModule) || []; - Object.defineProperty(context, 'module', { + ObjectDefineProperty(context, 'module', { configurable: true, writable: true, value: module }); - Object.defineProperty(context, 'require', { + ObjectDefineProperty(context, 'require', { configurable: true, writable: true, value: makeRequireFunction(module) @@ -934,7 +945,7 @@ REPLServer.prototype.resetContext = function() { this.lines = []; this.lines.level = []; - Object.defineProperty(this.context, '_', { + ObjectDefineProperty(this.context, '_', { configurable: true, get: () => this.last, set: (value) => { @@ -946,7 +957,7 @@ REPLServer.prototype.resetContext = function() { } }); - Object.defineProperty(this.context, '_error', { + ObjectDefineProperty(this.context, '_error', { configurable: true, get: () => this.lastError, set: (value) => { @@ -998,8 +1009,8 @@ function ArrayStream() { this.emit('data', `${data[n]}\n`); }; } -Object.setPrototypeOf(ArrayStream.prototype, Stream.prototype); -Object.setPrototypeOf(ArrayStream, Stream); +ObjectSetPrototypeOf(ArrayStream.prototype, Stream.prototype); +ObjectSetPrototypeOf(ArrayStream, Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function() {}; @@ -1102,7 +1113,7 @@ function complete(line, callback) { let filter; let match = line.match(/^\s*\.(\w*)$/); if (match) { - completionGroups.push(Object.keys(this.commands)); + completionGroups.push(ObjectKeys(this.commands)); completeOn = match[1]; if (match[1].length) { filter = match[1]; @@ -1111,7 +1122,7 @@ function complete(line, callback) { completionGroupsLoaded(); } else if (match = line.match(requireRE)) { // require('...') - const exts = Object.keys(this.context.require.extensions); + const exts = ObjectKeys(this.context.require.extensions); const indexRe = new RegExp('^index(?:' + exts.map(regexpEscape).join('|') + ')$'); const versionedFileNamesRe = /-\d+\.\d+/; @@ -1239,7 +1250,7 @@ function complete(line, callback) { if (this.useGlobal || vm.isContext(this.context)) { completionGroups.push(getGlobalLexicalScopeNames(this[kContextId])); let contextProto = this.context; - while (contextProto = Object.getPrototypeOf(contextProto)) { + while (contextProto = ObjectGetPrototypeOf(contextProto)) { completionGroups.push( filteredOwnPropertyNames.call(this, contextProto)); } @@ -1281,13 +1292,13 @@ function complete(line, callback) { let sentinel = 5; let p; if (typeof obj === 'object' || typeof obj === 'function') { - p = Object.getPrototypeOf(obj); + p = ObjectGetPrototypeOf(obj); } else { p = obj.constructor ? obj.constructor.prototype : null; } while (p !== null) { memberGroups.push(filteredOwnPropertyNames.call(this, p)); - p = Object.getPrototypeOf(p); + p = ObjectGetPrototypeOf(p); // Circular refs possible? Let's guard against that. sentinel--; if (sentinel <= 0) { @@ -1346,7 +1357,7 @@ function complete(line, callback) { group.sort(); for (let j = group.length - 1; j >= 0; j--) { const c = group[j]; - if (!ObjectPrototype.hasOwnProperty(uniq, c)) { + if (!ObjectPrototypeHasOwnProperty(uniq, c)) { completions.unshift(c); uniq[c] = true; } @@ -1542,9 +1553,9 @@ function defineDefaultCommands(repl) { repl.defineCommand('help', { help: 'Print this help message', action: function() { - const names = Object.keys(this.commands).sort(); + const names = ObjectKeys(this.commands).sort(); const longestNameLength = names.reduce( - (max, name) => Math.max(max, name.length), + (max, name) => MathMax(max, name.length), 0 ); for (let n = 0; n < names.length; n++) { @@ -1614,6 +1625,6 @@ function regexpEscape(s) { function Recoverable(err) { this.err = err; } -Object.setPrototypeOf(Recoverable.prototype, SyntaxError.prototype); -Object.setPrototypeOf(Recoverable, SyntaxError); +ObjectSetPrototypeOf(Recoverable.prototype, SyntaxError.prototype); +ObjectSetPrototypeOf(Recoverable, SyntaxError); exports.Recoverable = Recoverable; diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 7df50eb0178377..a070b4303de761 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperties, +} = primordials; const { Buffer } = require('buffer'); const { @@ -95,7 +97,7 @@ StringDecoder.prototype.text = function text(buf, offset) { return this.write(buf.slice(offset)); }; -Object.defineProperties(StringDecoder.prototype, { +ObjectDefineProperties(StringDecoder.prototype, { lastChar: { configurable: true, enumerable: true, diff --git a/lib/timers.js b/lib/timers.js index 584f6bc9529dfe..68327e2c3e5947 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -21,7 +21,9 @@ 'use strict'; -const { Math } = primordials; +const { + MathTrunc, +} = primordials; const { immediateInfo, @@ -77,7 +79,7 @@ function unenroll(item) { // That function could then be used by http and other similar modules. if (item[kRefed]) { // Compliment truncation during insert(). - const msecs = Math.trunc(item._idleTimeout); + const msecs = MathTrunc(item._idleTimeout); const list = timerListMap[msecs]; if (list !== undefined && L.isEmpty(list)) { debug('unenroll: list empty'); diff --git a/lib/tls.js b/lib/tls.js index c63c87a5dea6ae..d1ed771f33b358 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -21,7 +21,10 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectDefineProperty, + ObjectFreeze, +} = primordials; const { ERR_TLS_CERT_ALTNAME_INVALID, @@ -82,10 +85,10 @@ exports.getCiphers = internalUtil.cachedResult( let rootCertificates; function cacheRootCertificates() { - rootCertificates = Object.freeze(getRootCertificates()); + rootCertificates = ObjectFreeze(getRootCertificates()); } -Object.defineProperty(exports, 'rootCertificates', { +ObjectDefineProperty(exports, 'rootCertificates', { configurable: false, enumerable: true, get: () => { diff --git a/lib/tty.js b/lib/tty.js index cc22a3b499feca..3b431a1d881c99 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -21,7 +21,9 @@ 'use strict'; -const { Object } = primordials; +const { + ObjectSetPrototypeOf, +} = primordials; const net = require('net'); const { TTY, isTTY } = internalBinding('tty_wrap'); @@ -63,8 +65,8 @@ function ReadStream(fd, options) { this.isTTY = true; } -Object.setPrototypeOf(ReadStream.prototype, net.Socket.prototype); -Object.setPrototypeOf(ReadStream, net.Socket); +ObjectSetPrototypeOf(ReadStream.prototype, net.Socket.prototype); +ObjectSetPrototypeOf(ReadStream, net.Socket); ReadStream.prototype.setRawMode = function(flag) { flag = !!flag; @@ -110,8 +112,8 @@ function WriteStream(fd) { } } -Object.setPrototypeOf(WriteStream.prototype, net.Socket.prototype); -Object.setPrototypeOf(WriteStream, net.Socket); +ObjectSetPrototypeOf(WriteStream.prototype, net.Socket.prototype); +ObjectSetPrototypeOf(WriteStream, net.Socket); WriteStream.prototype.isTTY = true; diff --git a/lib/url.js b/lib/url.js index a7f8fa2203a4f9..735390dfd2e59b 100644 --- a/lib/url.js +++ b/lib/url.js @@ -21,7 +21,11 @@ 'use strict'; -const { Object, SafeSet } = primordials; +const { + ObjectCreate, + ObjectKeys, + SafeSet, +} = primordials; const { toASCII } = require('internal/idna'); const { encodeStr, hexTable } = require('internal/querystring'); @@ -247,7 +251,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { } } else if (parseQueryString) { this.search = null; - this.query = Object.create(null); + this.query = ObjectCreate(null); } return this; } @@ -436,7 +440,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { } else if (parseQueryString) { // No query string, but parseQueryString still requested this.search = null; - this.query = Object.create(null); + this.query = ObjectCreate(null); } const useQuestionIdx = @@ -676,7 +680,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { } const result = new Url(); - const tkeys = Object.keys(this); + const tkeys = ObjectKeys(this); for (let tk = 0; tk < tkeys.length; tk++) { const tkey = tkeys[tk]; result[tkey] = this[tkey]; @@ -695,7 +699,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { // Hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // Take everything except the protocol from relative - const rkeys = Object.keys(relative); + const rkeys = ObjectKeys(relative); for (let rk = 0; rk < rkeys.length; rk++) { const rkey = rkeys[rk]; if (rkey !== 'protocol') @@ -722,7 +726,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol.has(relative.protocol)) { - const keys = Object.keys(relative); + const keys = ObjectKeys(relative); for (let v = 0; v < keys.length; v++) { const k = keys[v]; result[k] = relative[k]; diff --git a/lib/util.js b/lib/util.js index 5ac2516f738b83..438fa5f1020937 100644 --- a/lib/util.js +++ b/lib/util.js @@ -21,7 +21,15 @@ 'use strict'; -const { Object, ObjectPrototype, Reflect } = primordials; +const { + ObjectDefineProperties, + ObjectDefineProperty, + ObjectGetOwnPropertyDescriptors, + ObjectKeys, + ObjectPrototypeToString, + ObjectSetPrototypeOf, + ReflectApply, +} = primordials; const { codes: { @@ -85,7 +93,7 @@ function isObject(arg) { } function isError(e) { - return ObjectPrototype.toString(e) === '[object Error]' || e instanceof Error; + return ObjectPrototypeToString(e) === '[object Error]' || e instanceof Error; } function isFunction(arg) { @@ -149,19 +157,19 @@ function inherits(ctor, superCtor) { throw new ERR_INVALID_ARG_TYPE('superCtor.prototype', 'Object', superCtor.prototype); } - Object.defineProperty(ctor, 'super_', { + ObjectDefineProperty(ctor, 'super_', { value: superCtor, writable: true, configurable: true }); - Object.setPrototypeOf(ctor.prototype, superCtor.prototype); + ObjectSetPrototypeOf(ctor.prototype, superCtor.prototype); } function _extend(target, source) { // Don't do anything if source isn't an object if (source === null || typeof source !== 'object') return target; - const keys = Object.keys(source); + const keys = ObjectKeys(source); let i = keys.length; while (i--) { target[keys[i]] = source[keys[i]]; @@ -193,15 +201,15 @@ function callbackify(original) { if (typeof maybeCb !== 'function') { throw new ERR_INVALID_ARG_TYPE('last argument', 'Function', maybeCb); } - const cb = (...args) => { Reflect.apply(maybeCb, this, args); }; + const cb = (...args) => { ReflectApply(maybeCb, this, args); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) - Reflect.apply(original, this, args) + ReflectApply(original, this, args) .then((ret) => process.nextTick(cb, null, ret), (rej) => process.nextTick(callbackifyOnRejected, rej, cb)); } - const descriptors = Object.getOwnPropertyDescriptors(original); + const descriptors = ObjectGetOwnPropertyDescriptors(original); // It is possible to manipulate a functions `length` or `name` property. This // guards against the manipulation. if (typeof descriptors.length.value === 'number') { @@ -210,7 +218,7 @@ function callbackify(original) { if (typeof descriptors.name.value === 'string') { descriptors.name.value += 'Callbackified'; } - Object.defineProperties(callbackified, descriptors); + ObjectDefineProperties(callbackified, descriptors); return callbackified; } diff --git a/lib/v8.js b/lib/v8.js index 32c2f3aa1b50ed..2156998d66d05b 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -14,7 +14,9 @@ 'use strict'; -const { ObjectPrototype } = primordials; +const { + ObjectPrototypeToString, +} = primordials; const { Buffer } = require('buffer'); const { validateString } = require('internal/validators'); @@ -220,7 +222,7 @@ const arrayBufferViewTypeToIndex = new Map(); { const dummy = new ArrayBuffer(); for (const [i, ctor] of arrayBufferViewTypes.entries()) { - const tag = ObjectPrototype.toString(new ctor(dummy)); + const tag = ObjectPrototypeToString(new ctor(dummy)); arrayBufferViewTypeToIndex.set(tag, i); } } @@ -239,7 +241,7 @@ class DefaultSerializer extends Serializer { if (abView.constructor === Buffer) { i = bufferConstructorIndex; } else { - const tag = ObjectPrototype.toString(abView); + const tag = ObjectPrototypeToString(abView); i = arrayBufferViewTypeToIndex.get(tag); if (i === undefined) { diff --git a/lib/vm.js b/lib/vm.js index 8d44a92c804a21..d12a460df69c39 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -21,7 +21,10 @@ 'use strict'; -const { Array, ArrayPrototype } = primordials; +const { + ArrayIsArray, + ArrayPrototypeForEach, +} = primordials; const { ContextifyScript, @@ -309,11 +312,11 @@ function runInThisContext(code, options) { function compileFunction(code, params, options = {}) { validateString(code, 'code'); if (params !== undefined) { - if (!Array.isArray(params)) { + if (!ArrayIsArray(params)) { throw new ERR_INVALID_ARG_TYPE('params', 'Array', params); } - ArrayPrototype.forEach(params, - (param, i) => validateString(param, `params[${i}]`)); + ArrayPrototypeForEach(params, + (param, i) => validateString(param, `params[${i}]`)); } const { @@ -356,14 +359,14 @@ function compileFunction(code, params, options = {}) { ); } } - if (!Array.isArray(contextExtensions)) { + if (!ArrayIsArray(contextExtensions)) { throw new ERR_INVALID_ARG_TYPE( 'options.contextExtensions', 'Array', contextExtensions ); } - ArrayPrototype.forEach(contextExtensions, (extension, i) => { + ArrayPrototypeForEach(contextExtensions, (extension, i) => { if (typeof extension !== 'object') { throw new ERR_INVALID_ARG_TYPE( `options.contextExtensions[${i}]`, diff --git a/lib/zlib.js b/lib/zlib.js index 264d1c95c2725f..8892abaddb6344 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -21,7 +21,15 @@ 'use strict'; -const { Math, Object } = primordials; +const { + MathMax, + ObjectDefineProperties, + ObjectDefineProperty, + ObjectFreeze, + ObjectGetPrototypeOf, + ObjectKeys, + ObjectSetPrototypeOf, +} = primordials; const { codes: { @@ -80,7 +88,7 @@ const codes = { Z_VERSION_ERROR: constants.Z_VERSION_ERROR }; -const ckeys = Object.keys(codes); +const ckeys = ObjectKeys(codes); for (var ck = 0; ck < ckeys.length; ck++) { var ckey = ckeys[ck]; codes[codes[ckey]] = ckey; @@ -92,7 +100,7 @@ function zlibBuffer(engine, buffer, callback) { // Streams do not support non-Buffer ArrayBufferViews yet. Convert it to a // Buffer without copying. if (isArrayBufferView(buffer) && - Object.getPrototypeOf(buffer) !== Buffer.prototype) { + ObjectGetPrototypeOf(buffer) !== Buffer.prototype) { buffer = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); } else if (isAnyArrayBuffer(buffer)) { buffer = Buffer.from(buffer); @@ -267,10 +275,10 @@ function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { this.once('end', _close.bind(null, this)); this._info = opts && opts.info; } -Object.setPrototypeOf(ZlibBase.prototype, Transform.prototype); -Object.setPrototypeOf(ZlibBase, Transform); +ObjectSetPrototypeOf(ZlibBase.prototype, Transform.prototype); +ObjectSetPrototypeOf(ZlibBase, Transform); -Object.defineProperty(ZlibBase.prototype, '_closed', { +ObjectDefineProperty(ZlibBase.prototype, '_closed', { configurable: true, enumerable: true, get() { @@ -282,7 +290,7 @@ Object.defineProperty(ZlibBase.prototype, '_closed', { // perspective, but it is inconsistent with all other streams exposed by Node.js // that have this concept, where it stands for the number of bytes read // *from* the stream (that is, net.Socket/tls.Socket & file system streams). -Object.defineProperty(ZlibBase.prototype, 'bytesRead', { +ObjectDefineProperty(ZlibBase.prototype, 'bytesRead', { configurable: true, enumerable: true, get: deprecate(function() { @@ -658,8 +666,8 @@ function Zlib(opts, mode) { this._level = level; this._strategy = strategy; } -Object.setPrototypeOf(Zlib.prototype, ZlibBase.prototype); -Object.setPrototypeOf(Zlib, ZlibBase); +ObjectSetPrototypeOf(Zlib.prototype, ZlibBase.prototype); +ObjectSetPrototypeOf(Zlib, ZlibBase); // This callback is used by `.params()` to wait until a full flush happened // before adjusting the parameters. In particular, the call to the native @@ -694,32 +702,32 @@ function Deflate(opts) { return new Deflate(opts); Zlib.call(this, opts, DEFLATE); } -Object.setPrototypeOf(Deflate.prototype, Zlib.prototype); -Object.setPrototypeOf(Deflate, Zlib); +ObjectSetPrototypeOf(Deflate.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Deflate, Zlib); function Inflate(opts) { if (!(this instanceof Inflate)) return new Inflate(opts); Zlib.call(this, opts, INFLATE); } -Object.setPrototypeOf(Inflate.prototype, Zlib.prototype); -Object.setPrototypeOf(Inflate, Zlib); +ObjectSetPrototypeOf(Inflate.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Inflate, Zlib); function Gzip(opts) { if (!(this instanceof Gzip)) return new Gzip(opts); Zlib.call(this, opts, GZIP); } -Object.setPrototypeOf(Gzip.prototype, Zlib.prototype); -Object.setPrototypeOf(Gzip, Zlib); +ObjectSetPrototypeOf(Gzip.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Gzip, Zlib); function Gunzip(opts) { if (!(this instanceof Gunzip)) return new Gunzip(opts); Zlib.call(this, opts, GUNZIP); } -Object.setPrototypeOf(Gunzip.prototype, Zlib.prototype); -Object.setPrototypeOf(Gunzip, Zlib); +ObjectSetPrototypeOf(Gunzip.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Gunzip, Zlib); function DeflateRaw(opts) { if (opts && opts.windowBits === 8) opts.windowBits = 9; @@ -727,24 +735,24 @@ function DeflateRaw(opts) { return new DeflateRaw(opts); Zlib.call(this, opts, DEFLATERAW); } -Object.setPrototypeOf(DeflateRaw.prototype, Zlib.prototype); -Object.setPrototypeOf(DeflateRaw, Zlib); +ObjectSetPrototypeOf(DeflateRaw.prototype, Zlib.prototype); +ObjectSetPrototypeOf(DeflateRaw, Zlib); function InflateRaw(opts) { if (!(this instanceof InflateRaw)) return new InflateRaw(opts); Zlib.call(this, opts, INFLATERAW); } -Object.setPrototypeOf(InflateRaw.prototype, Zlib.prototype); -Object.setPrototypeOf(InflateRaw, Zlib); +ObjectSetPrototypeOf(InflateRaw.prototype, Zlib.prototype); +ObjectSetPrototypeOf(InflateRaw, Zlib); function Unzip(opts) { if (!(this instanceof Unzip)) return new Unzip(opts); Zlib.call(this, opts, UNZIP); } -Object.setPrototypeOf(Unzip.prototype, Zlib.prototype); -Object.setPrototypeOf(Unzip, Zlib); +ObjectSetPrototypeOf(Unzip.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Unzip, Zlib); function createConvenienceMethod(ctor, sync) { if (sync) { @@ -762,7 +770,7 @@ function createConvenienceMethod(ctor, sync) { } } -const kMaxBrotliParam = Math.max(...Object.keys(constants).map((key) => { +const kMaxBrotliParam = MathMax(...ObjectKeys(constants).map((key) => { return key.startsWith('BROTLI_PARAM_') ? constants[key] : 0; })); @@ -778,7 +786,7 @@ function Brotli(opts, mode) { brotliInitParamsArray.fill(-1); if (opts && opts.params) { - for (const origKey of Object.keys(opts.params)) { + for (const origKey of ObjectKeys(opts.params)) { const key = +origKey; if (Number.isNaN(key) || key < 0 || key > kMaxBrotliParam || (brotliInitParamsArray[key] | 0) !== -1) { @@ -806,24 +814,24 @@ function Brotli(opts, mode) { ZlibBase.call(this, opts, mode, handle, brotliDefaultOpts); } -Object.setPrototypeOf(Brotli.prototype, Zlib.prototype); -Object.setPrototypeOf(Brotli, Zlib); +ObjectSetPrototypeOf(Brotli.prototype, Zlib.prototype); +ObjectSetPrototypeOf(Brotli, Zlib); function BrotliCompress(opts) { if (!(this instanceof BrotliCompress)) return new BrotliCompress(opts); Brotli.call(this, opts, BROTLI_ENCODE); } -Object.setPrototypeOf(BrotliCompress.prototype, Brotli.prototype); -Object.setPrototypeOf(BrotliCompress, Brotli); +ObjectSetPrototypeOf(BrotliCompress.prototype, Brotli.prototype); +ObjectSetPrototypeOf(BrotliCompress, Brotli); function BrotliDecompress(opts) { if (!(this instanceof BrotliDecompress)) return new BrotliDecompress(opts); Brotli.call(this, opts, BROTLI_DECODE); } -Object.setPrototypeOf(BrotliDecompress.prototype, Brotli.prototype); -Object.setPrototypeOf(BrotliDecompress, Brotli); +ObjectSetPrototypeOf(BrotliDecompress.prototype, Brotli.prototype); +ObjectSetPrototypeOf(BrotliDecompress, Brotli); function createProperty(ctor) { @@ -838,7 +846,7 @@ function createProperty(ctor) { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. -Object.defineProperty(binding.Zlib.prototype, 'jsref', { +ObjectDefineProperty(binding.Zlib.prototype, 'jsref', { get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); @@ -876,7 +884,7 @@ module.exports = { brotliDecompressSync: createConvenienceMethod(BrotliDecompress, true), }; -Object.defineProperties(module.exports, { +ObjectDefineProperties(module.exports, { createDeflate: createProperty(Deflate), createInflate: createProperty(Inflate), createDeflateRaw: createProperty(DeflateRaw), @@ -894,17 +902,17 @@ Object.defineProperties(module.exports, { codes: { enumerable: true, writable: false, - value: Object.freeze(codes) + value: ObjectFreeze(codes) } }); // These should be considered deprecated // expose all the zlib constants -const bkeys = Object.keys(constants); +const bkeys = ObjectKeys(constants); for (var bk = 0; bk < bkeys.length; bk++) { var bkey = bkeys[bk]; if (bkey.startsWith('BROTLI')) continue; - Object.defineProperty(module.exports, bkey, { + ObjectDefineProperty(module.exports, bkey, { enumerable: false, value: constants[bkey], writable: false }); }