diff --git a/packages/datadog-instrumentations/src/aerospike.js b/packages/datadog-instrumentations/src/aerospike.js index ba310b6e2de..84e7f4cc3d3 100644 --- a/packages/datadog-instrumentations/src/aerospike.js +++ b/packages/datadog-instrumentations/src/aerospike.js @@ -12,7 +12,7 @@ function wrapCreateCommand (createCommand) { if (typeof createCommand !== 'function') return createCommand return function commandWithTrace () { - const CommandClass = createCommand.apply(this, arguments) + const CommandClass = Reflect.apply(createCommand, this, arguments) if (!CommandClass) return CommandClass diff --git a/packages/datadog-instrumentations/src/amqp10.js b/packages/datadog-instrumentations/src/amqp10.js index 5c25901541c..feb7d6c637a 100644 --- a/packages/datadog-instrumentations/src/amqp10.js +++ b/packages/datadog-instrumentations/src/amqp10.js @@ -13,13 +13,13 @@ addHook({ name: 'amqp10', file: 'lib/sender_link.js', versions: ['>=3'] }, Sende const errorCh = channel('apm:amqp10:send:error') shimmer.wrap(SenderLink.prototype, 'send', send => function (msg, options) { if (!startCh.hasSubscribers) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { startCh.publish({ link: this }) try { - const promise = send.apply(this, arguments) + const promise = Reflect.apply(send, this, arguments) if (!promise) { finish(finishCh, errorCh) @@ -45,13 +45,13 @@ addHook({ name: 'amqp10', file: 'lib/receiver_link.js', versions: ['>=3'] }, Rec const errorCh = channel('apm:amqp10:receive:error') shimmer.wrap(ReceiverLink.prototype, '_messageReceived', messageReceived => function (transferFrame) { if (!transferFrame || transferFrame.aborted || transferFrame.more) { - return messageReceived.apply(this, arguments) + return Reflect.apply(messageReceived, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { startCh.publish({ link: this }) try { - return messageReceived.apply(this, arguments) + return Reflect.apply(messageReceived, this, arguments) } catch (err) { errorCh.publish(err) throw err diff --git a/packages/datadog-instrumentations/src/amqplib.js b/packages/datadog-instrumentations/src/amqplib.js index 73275a0cd8c..cec37ba2045 100644 --- a/packages/datadog-instrumentations/src/amqplib.js +++ b/packages/datadog-instrumentations/src/amqplib.js @@ -27,7 +27,7 @@ addHook({ name: 'amqplib', file: 'lib/defs.js', versions: [MIN_VERSION] }, defs addHook({ name: 'amqplib', file: 'lib/channel_model.js', versions: [MIN_VERSION] }, x => { shimmer.wrap(x.Channel.prototype, 'get', getMessage => function (queue, options) { - return getMessage.apply(this, arguments).then(message => { + return Reflect.apply(getMessage, this, arguments).then(message => { if (message === null) { return message } @@ -39,7 +39,7 @@ addHook({ name: 'amqplib', file: 'lib/channel_model.js', versions: [MIN_VERSION] }) shimmer.wrap(x.Channel.prototype, 'consume', consume => function (queue, callback, options) { if (!startCh.hasSubscribers) { - return consume.apply(this, arguments) + return Reflect.apply(consume, this, arguments) } arguments[1] = (message, ...args) => { if (message === null) { @@ -50,7 +50,7 @@ addHook({ name: 'amqplib', file: 'lib/channel_model.js', versions: [MIN_VERSION] finishCh.publish() return result } - return consume.apply(this, arguments) + return Reflect.apply(consume, this, arguments) }) return x }) @@ -58,7 +58,7 @@ addHook({ name: 'amqplib', file: 'lib/channel_model.js', versions: [MIN_VERSION] addHook({ name: 'amqplib', file: 'lib/callback_model.js', versions: [MIN_VERSION] }, channel => { shimmer.wrap(channel.Channel.prototype, 'get', getMessage => function (queue, options, callback) { if (!startCh.hasSubscribers) { - return getMessage.apply(this, arguments) + return Reflect.apply(getMessage, this, arguments) } arguments[2] = (error, message, ...args) => { if (error !== null || message === null) { @@ -69,11 +69,11 @@ addHook({ name: 'amqplib', file: 'lib/callback_model.js', versions: [MIN_VERSION finishCh.publish() return result } - return getMessage.apply(this, arguments) + return Reflect.apply(getMessage, this, arguments) }) shimmer.wrap(channel.Channel.prototype, 'consume', consume => function (queue, callback) { if (!startCh.hasSubscribers) { - return consume.apply(this, arguments) + return Reflect.apply(consume, this, arguments) } arguments[1] = (message, ...args) => { if (message === null) { @@ -84,7 +84,7 @@ addHook({ name: 'amqplib', file: 'lib/callback_model.js', versions: [MIN_VERSION finishCh.publish() return result } - return consume.apply(this, arguments) + return Reflect.apply(consume, this, arguments) }) return channel }) diff --git a/packages/datadog-instrumentations/src/apollo-server-core.js b/packages/datadog-instrumentations/src/apollo-server-core.js index 3f075ab6938..c1ca481d022 100644 --- a/packages/datadog-instrumentations/src/apollo-server-core.js +++ b/packages/datadog-instrumentations/src/apollo-server-core.js @@ -12,7 +12,7 @@ addHook({ name: 'apollo-server-core', file: 'dist/runHttpQuery.js', versions: [' shimmer.wrap(runHttpQueryModule, 'runHttpQuery', function wrapRunHttpQuery (originalRunHttpQuery) { return async function runHttpQuery () { if (!requestChannel.start.hasSubscribers) { - return originalRunHttpQuery.apply(this, arguments) + return Reflect.apply(originalRunHttpQuery, this, arguments) } const abortController = new AbortController() diff --git a/packages/datadog-instrumentations/src/apollo-server.js b/packages/datadog-instrumentations/src/apollo-server.js index 5a41903df91..0aec5ca28c0 100644 --- a/packages/datadog-instrumentations/src/apollo-server.js +++ b/packages/datadog-instrumentations/src/apollo-server.js @@ -14,7 +14,7 @@ let HeaderMap function wrapExecuteHTTPGraphQLRequest (originalExecuteHTTPGraphQLRequest) { return async function executeHTTPGraphQLRequest () { if (!HeaderMap || !requestChannel.start.hasSubscribers) { - return originalExecuteHTTPGraphQLRequest.apply(this, arguments) + return Reflect.apply(originalExecuteHTTPGraphQLRequest, this, arguments) } const abortController = new AbortController() @@ -53,11 +53,11 @@ function wrapExecuteHTTPGraphQLRequest (originalExecuteHTTPGraphQLRequest) { function apolloExpress4Hook (express4) { shimmer.wrap(express4, 'expressMiddleware', function wrapExpressMiddleware (originalExpressMiddleware) { return function expressMiddleware (server, options) { - const originalMiddleware = originalExpressMiddleware.apply(this, arguments) + const originalMiddleware = Reflect.apply(originalExpressMiddleware, this, arguments) return shimmer.wrapFunction(originalMiddleware, originalMiddleware => function (req, res, next) { if (!graphqlMiddlewareChannel.start.hasSubscribers) { - return originalMiddleware.apply(this, arguments) + return Reflect.apply(originalMiddleware, this, arguments) } return graphqlMiddlewareChannel.traceSync(originalMiddleware, { req }, this, ...arguments) diff --git a/packages/datadog-instrumentations/src/avsc.js b/packages/datadog-instrumentations/src/avsc.js index 6d71b1744bf..2cec6f2a9f7 100644 --- a/packages/datadog-instrumentations/src/avsc.js +++ b/packages/datadog-instrumentations/src/avsc.js @@ -8,19 +8,19 @@ const deserializeChannel = dc.channel('apm:avsc:deserialize-end') function wrapSerialization (Type) { shimmer.wrap(Type.prototype, 'toBuffer', original => function () { if (!serializeChannel.hasSubscribers) { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } serializeChannel.publish({ messageClass: this }) - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) }) } function wrapDeserialization (Type) { shimmer.wrap(Type.prototype, 'fromBuffer', original => function () { if (!deserializeChannel.hasSubscribers) { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) deserializeChannel.publish({ messageClass: result }) return result }) diff --git a/packages/datadog-instrumentations/src/aws-sdk.js b/packages/datadog-instrumentations/src/aws-sdk.js index d6fbccb39a8..adea8af7c06 100644 --- a/packages/datadog-instrumentations/src/aws-sdk.js +++ b/packages/datadog-instrumentations/src/aws-sdk.js @@ -9,12 +9,12 @@ const shimmer = require('../../datadog-shimmer') function wrapRequest (send) { return function wrappedRequest (cb) { - if (!this.service) return send.apply(this, arguments) + if (!this.service) return Reflect.apply(send, this, arguments) const serviceIdentifier = this.service.serviceIdentifier const channelSuffix = getChannelSuffix(serviceIdentifier) const startCh = channel(`apm:aws:request:start:${channelSuffix}`) - if (!startCh.hasSubscribers) return send.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(send, this, arguments) const innerAr = new AsyncResource('apm:aws:request:inner') const outerAr = new AsyncResource('apm:aws:request:outer') @@ -35,7 +35,7 @@ function wrapRequest (send) { if (typeof cb === 'function') { arguments[0] = wrapCb(cb, channelSuffix, this, outerAr) } - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) }) } } @@ -48,7 +48,7 @@ function wrapDeserialize (deserialize, channelSuffix) { headersCh.publish({ headers: response.headers }) } - return deserialize.apply(this, arguments) + return Reflect.apply(deserialize, this, arguments) } } @@ -99,7 +99,7 @@ function wrapSmithySend (send) { outerAr.runInAsyncScope(() => { responseStartChannel.publish(message) - cb.apply(this, arguments) + Reflect.apply(cb, this, arguments) if (message.needsFinish) { responseFinishChannel.publish(message.response.error) @@ -135,11 +135,11 @@ function wrapCb (cb, serviceName, request, ar) { channel(`apm:aws:response:start:${serviceName}`).publish(obj) // TODO(bengl) make this work without needing a needsFinish property added to the object if (!obj.needsFinish) { - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) } const finishChannel = channel(`apm:aws:response:finish:${serviceName}`) try { - let result = cb.apply(this, arguments) + let result = Reflect.apply(cb, this, arguments) if (result && result.then) { result = result.then(x => { finishChannel.publish() @@ -205,7 +205,7 @@ addHook({ name: '@aws-sdk/smithy-client', versions: ['>=3'] }, smithy => { addHook({ name: 'aws-sdk', versions: ['>=2.3.0'] }, AWS => { shimmer.wrap(AWS.config, 'setPromisesDependency', setPromisesDependency => { return function wrappedSetPromisesDependency (dep) { - const result = setPromisesDependency.apply(this, arguments) + const result = Reflect.apply(setPromisesDependency, this, arguments) shimmer.wrap(AWS.Request.prototype, 'promise', wrapRequest) return result } diff --git a/packages/datadog-instrumentations/src/azure-functions.js b/packages/datadog-instrumentations/src/azure-functions.js index 791d3a9025f..f0f040b8f47 100644 --- a/packages/datadog-instrumentations/src/azure-functions.js +++ b/packages/datadog-instrumentations/src/azure-functions.js @@ -32,7 +32,7 @@ function wrapHandler (method) { const handler = arg arguments[1] = shimmer.wrapFunction(handler, handler => traceHandler(handler, name, method.name)) } - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/bluebird.js b/packages/datadog-instrumentations/src/bluebird.js index cf0205dd5c0..a3b78a7a4fe 100644 --- a/packages/datadog-instrumentations/src/bluebird.js +++ b/packages/datadog-instrumentations/src/bluebird.js @@ -7,7 +7,7 @@ const shimmer = require('../../datadog-shimmer') function createGetNewLibraryCopyWrap (originalLib) { return function wrapGetNewLibraryCopy (getNewLibraryCopy) { return function getNewLibraryCopyWithTrace () { - const libraryCopy = getNewLibraryCopy.apply(this, arguments) + const libraryCopy = Reflect.apply(getNewLibraryCopy, this, arguments) shimmer.wrap(libraryCopy.prototype, '_then', wrapThen) shimmer.wrap(libraryCopy, 'getNewLibraryCopy', createGetNewLibraryCopyWrap(originalLib)) return libraryCopy diff --git a/packages/datadog-instrumentations/src/body-parser.js b/packages/datadog-instrumentations/src/body-parser.js index ab51accb44b..95e58f1312a 100644 --- a/packages/datadog-instrumentations/src/body-parser.js +++ b/packages/datadog-instrumentations/src/body-parser.js @@ -16,7 +16,7 @@ function publishRequestBodyAndNext (req, res, next) { if (abortController.signal.aborted) return } - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } @@ -28,7 +28,7 @@ addHook({ return shimmer.wrapFunction(read, read => function (req, res, next) { const nextResource = new AsyncResource('bound-anonymous-fn') arguments[2] = nextResource.bind(publishRequestBodyAndNext(req, res, next)) - return read.apply(this, arguments) + return Reflect.apply(read, this, arguments) }) }) @@ -39,6 +39,6 @@ addHook({ }, read => { return shimmer.wrapFunction(read, read => function (req, res, next) { arguments[2] = publishRequestBodyAndNext(req, res, next) - return read.apply(this, arguments) + return Reflect.apply(read, this, arguments) }) }) diff --git a/packages/datadog-instrumentations/src/bunyan.js b/packages/datadog-instrumentations/src/bunyan.js index 039e7740c7a..11d0cda0018 100644 --- a/packages/datadog-instrumentations/src/bunyan.js +++ b/packages/datadog-instrumentations/src/bunyan.js @@ -15,7 +15,7 @@ addHook({ name: 'bunyan', versions: ['>=1'] }, Logger => { logCh.publish(payload) arguments[0] = payload.message } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } }) return Logger diff --git a/packages/datadog-instrumentations/src/cassandra-driver.js b/packages/datadog-instrumentations/src/cassandra-driver.js index a4684a01260..79fb1381942 100644 --- a/packages/datadog-instrumentations/src/cassandra-driver.js +++ b/packages/datadog-instrumentations/src/cassandra-driver.js @@ -15,7 +15,7 @@ const connectCh = channel('apm:cassandra-driver:query:connect') addHook({ name: 'cassandra-driver', versions: ['>=3.0.0'] }, cassandra => { shimmer.wrap(cassandra.Client.prototype, 'batch', batch => function (queries, options, callback) { if (!startCh.hasSubscribers) { - return batch.apply(this, arguments) + return Reflect.apply(batch, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -31,7 +31,7 @@ addHook({ name: 'cassandra-driver', versions: ['>=3.0.0'] }, cassandra => { const contactPoints = this.options && this.options.contactPoints startCh.publish({ keyspace: this.keyspace, query: queries, contactPoints }) try { - const res = batch.apply(this, arguments) + const res = Reflect.apply(batch, this, arguments) if (typeof res === 'function' || !res) { return wrapCallback(finishCh, errorCh, asyncResource, res) } else { @@ -53,13 +53,13 @@ addHook({ name: 'cassandra-driver', versions: ['>=3.0.0'] }, cassandra => { addHook({ name: 'cassandra-driver', versions: ['>=4.4'] }, cassandra => { shimmer.wrap(cassandra.Client.prototype, '_execute', _execute => function (query, params, execOptions, callback) { if (!startCh.hasSubscribers) { - return _execute.apply(this, arguments) + return Reflect.apply(_execute, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { const contactPoints = this.options && this.options.contactPoints startCh.publish({ keyspace: this.keyspace, query, contactPoints }) - const promise = _execute.apply(this, arguments) + const promise = Reflect.apply(_execute, this, arguments) const promiseAsyncResource = new AsyncResource('bound-anonymous-fn') @@ -77,7 +77,7 @@ addHook({ name: 'cassandra-driver', versions: ['3 - 4.3'] }, cassandra => { shimmer.wrap(cassandra.Client.prototype, '_innerExecute', _innerExecute => function (query, params, execOptions, callback) { if (!startCh.hasSubscribers) { - return _innerExecute.apply(this, arguments) + return Reflect.apply(_innerExecute, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -86,7 +86,7 @@ addHook({ name: 'cassandra-driver', versions: ['3 - 4.3'] }, cassandra => { } if (!isValid(arguments)) { - return _innerExecute.apply(this, arguments) + return Reflect.apply(_innerExecute, this, arguments) } return asyncResource.runInAsyncScope(() => { @@ -102,7 +102,7 @@ addHook({ name: 'cassandra-driver', versions: ['3 - 4.3'] }, cassandra => { } try { - return _innerExecute.apply(this, arguments) + return Reflect.apply(_innerExecute, this, arguments) } catch (e) { finish(finishCh, errorCh, e) throw e @@ -116,10 +116,10 @@ addHook({ name: 'cassandra-driver', versions: ['3 - 4.3'] }, cassandra => { addHook({ name: 'cassandra-driver', versions: ['>=3.3'], file: 'lib/request-execution.js' }, RequestExecution => { shimmer.wrap(RequestExecution.prototype, '_sendOnConnection', _sendOnConnection => function () { if (!startCh.hasSubscribers) { - return _sendOnConnection.apply(this, arguments) + return Reflect.apply(_sendOnConnection, this, arguments) } connectCh.publish({ hostname: this._connection.address, port: this._connection.port }) - return _sendOnConnection.apply(this, arguments) + return Reflect.apply(_sendOnConnection, this, arguments) }) return RequestExecution }) @@ -127,23 +127,23 @@ addHook({ name: 'cassandra-driver', versions: ['>=3.3'], file: 'lib/request-exec addHook({ name: 'cassandra-driver', versions: ['3.3 - 4.3'], file: 'lib/request-execution.js' }, RequestExecution => { shimmer.wrap(RequestExecution.prototype, 'start', start => function (getHostCallback) { if (!startCh.hasSubscribers) { - return getHostCallback.apply(this, arguments) + return Reflect.apply(getHostCallback, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') const execution = this if (!isRequestValid(this, arguments, 1)) { - return start.apply(this, arguments) + return Reflect.apply(start, this, arguments) } getHostCallback = asyncResource.bind(getHostCallback) arguments[0] = AsyncResource.bind(function () { connectCh.publish({ hostname: execution._connection.address, port: execution._connection.port }) - return getHostCallback.apply(this, arguments) + return Reflect.apply(getHostCallback, this, arguments) }) - return start.apply(this, arguments) + return Reflect.apply(start, this, arguments) }) return RequestExecution }) @@ -151,12 +151,12 @@ addHook({ name: 'cassandra-driver', versions: ['3.3 - 4.3'], file: 'lib/request- addHook({ name: 'cassandra-driver', versions: ['3 - 3.2'], file: 'lib/request-handler.js' }, RequestHandler => { shimmer.wrap(RequestHandler.prototype, 'send', send => function (request, options, callback) { if (!startCh.hasSubscribers) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const handler = this if (!isRequestValid(this, arguments, 3)) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -164,10 +164,10 @@ addHook({ name: 'cassandra-driver', versions: ['3 - 3.2'], file: 'lib/request-ha arguments[2] = AsyncResource.bind(function () { connectCh.publish({ hostname: handler.connection.address, port: handler.connection.port }) - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) }) - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) }) return RequestHandler }) @@ -183,7 +183,7 @@ function wrapCallback (finishCh, errorCh, asyncResource, callback) { return shimmer.wrapFunction(callback, callback => asyncResource.bind(function (err) { finish(finishCh, errorCh, err) if (callback) { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) } })) } diff --git a/packages/datadog-instrumentations/src/child_process.js b/packages/datadog-instrumentations/src/child_process.js index f7224953367..6d47a037c45 100644 --- a/packages/datadog-instrumentations/src/child_process.js +++ b/packages/datadog-instrumentations/src/child_process.js @@ -93,7 +93,7 @@ function wrapChildProcessSyncMethod (returnError, shell = false) { return function wrapMethod (childProcessMethod) { return function () { if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) { - return childProcessMethod.apply(this, arguments) + return Reflect.apply(childProcessMethod, this, arguments) } const childProcessInfo = normalizeArgs(arguments, shell) @@ -112,7 +112,7 @@ function wrapChildProcessSyncMethod (returnError, shell = false) { return returnError(error, context) } - const result = childProcessMethod.apply(this, arguments) + const result = Reflect.apply(childProcessMethod, this, arguments) context.result = result return result @@ -132,7 +132,7 @@ function wrapChildProcessSyncMethod (returnError, shell = false) { function wrapChildProcessCustomPromisifyMethod (customPromisifyMethod, shell) { return function () { if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) { - return customPromisifyMethod.apply(this, arguments) + return Reflect.apply(customPromisifyMethod, this, arguments) } const childProcessInfo = normalizeArgs(arguments, shell) @@ -152,7 +152,7 @@ function wrapChildProcessCustomPromisifyMethod (customPromisifyMethod, shell) { result = Promise.reject(abortController.signal.reason || new Error('Aborted')) } else { try { - result = customPromisifyMethod.apply(this, arguments) + result = Reflect.apply(customPromisifyMethod, this, arguments) } catch (error) { error.publish({ ...context, error }) throw error @@ -186,7 +186,7 @@ function wrapChildProcessAsyncMethod (ChildProcess, shell = false) { return function wrapMethod (childProcessMethod) { function wrappedChildProcessMethod () { if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) { - return childProcessMethod.apply(this, arguments) + return Reflect.apply(childProcessMethod, this, arguments) } const childProcessInfo = normalizeArgs(arguments, shell) @@ -221,7 +221,7 @@ function wrapChildProcessAsyncMethod (ChildProcess, shell = false) { childProcess.emit('close') }) } else { - childProcess = childProcessMethod.apply(this, arguments) + childProcess = Reflect.apply(childProcessMethod, this, arguments) } if (childProcess) { diff --git a/packages/datadog-instrumentations/src/connect.js b/packages/datadog-instrumentations/src/connect.js index 507811f6dd3..5797167c0dd 100644 --- a/packages/datadog-instrumentations/src/connect.js +++ b/packages/datadog-instrumentations/src/connect.js @@ -29,7 +29,7 @@ function wrapUse (use) { if (typeof use !== 'function') return use return function useWithTrace (route, fn) { - const result = use.apply(this, arguments) + const result = Reflect.apply(use, this, arguments) if (!this || !Array.isArray(this.stack)) return result @@ -50,7 +50,7 @@ function wrapHandle (handle) { handleChannel.publish({ req, res }) } - return handle.apply(this, arguments) + return Reflect.apply(handle, this, arguments) } } @@ -60,7 +60,7 @@ function wrapLayerHandle (layer) { const original = layer.handle return shimmer.wrapFunction(original, original => function () { - if (!enterChannel.hasSubscribers) return original.apply(this, arguments) + if (!enterChannel.hasSubscribers) return Reflect.apply(original, this, arguments) const lastIndex = arguments.length - 1 const name = original._name || original.name @@ -76,7 +76,7 @@ function wrapLayerHandle (layer) { enterChannel.publish({ name, req, route }) try { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } catch (error) { errorChannel.publish({ req, error }) nextChannel.publish({ req }) @@ -98,7 +98,7 @@ function wrapNext (req, next) { nextChannel.publish({ req }) finishChannel.publish({ req }) - next.apply(this, arguments) + Reflect.apply(next, this, arguments) }) } diff --git a/packages/datadog-instrumentations/src/cookie-parser.js b/packages/datadog-instrumentations/src/cookie-parser.js index 09b3e18b71f..82c6ed25417 100644 --- a/packages/datadog-instrumentations/src/cookie-parser.js +++ b/packages/datadog-instrumentations/src/cookie-parser.js @@ -17,7 +17,7 @@ function publishRequestCookieAndNext (req, res, next) { if (abortController.signal.aborted) return } - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } @@ -26,11 +26,11 @@ addHook({ versions: ['>=1.0.0'] }, cookieParser => { return shimmer.wrapFunction(cookieParser, cookieParser => function () { - const cookieMiddleware = cookieParser.apply(this, arguments) + const cookieMiddleware = Reflect.apply(cookieParser, this, arguments) return shimmer.wrapFunction(cookieMiddleware, cookieMiddleware => function (req, res, next) { arguments[2] = publishRequestCookieAndNext(req, res, next) - return cookieMiddleware.apply(this, arguments) + return Reflect.apply(cookieMiddleware, this, arguments) }) }) }) diff --git a/packages/datadog-instrumentations/src/cookie.js b/packages/datadog-instrumentations/src/cookie.js index 291045d49ab..4b85f9a493d 100644 --- a/packages/datadog-instrumentations/src/cookie.js +++ b/packages/datadog-instrumentations/src/cookie.js @@ -7,7 +7,7 @@ const cookieParseCh = channel('datadog:cookie:parse:finish') function wrapParse (originalParse) { return function () { - const cookies = originalParse.apply(this, arguments) + const cookies = Reflect.apply(originalParse, this, arguments) if (cookieParseCh.hasSubscribers && cookies) { cookieParseCh.publish({ cookies }) } diff --git a/packages/datadog-instrumentations/src/couchbase.js b/packages/datadog-instrumentations/src/couchbase.js index 2cc30836738..83df8b84989 100644 --- a/packages/datadog-instrumentations/src/couchbase.js +++ b/packages/datadog-instrumentations/src/couchbase.js @@ -26,7 +26,7 @@ function wrapAllNames (names, action) { // semver >=2 <3 function wrapMaybeInvoke (_maybeInvoke) { const wrapped = function (fn, args) { - if (!Array.isArray(args)) return _maybeInvoke.apply(this, arguments) + if (!Array.isArray(args)) return Reflect.apply(_maybeInvoke, this, arguments) const callbackIndex = args.length - 1 const callback = args[callbackIndex] @@ -35,7 +35,7 @@ function wrapMaybeInvoke (_maybeInvoke) { args[callbackIndex] = AsyncResource.bind(callback) } - return _maybeInvoke.apply(this, arguments) + return Reflect.apply(_maybeInvoke, this, arguments) } return wrapped } @@ -48,7 +48,7 @@ function wrapQuery (query) { arguments[arguments.length - 1] = callback } - const res = query.apply(this, arguments) + const res = Reflect.apply(query, this, arguments) return res } return wrapped @@ -61,12 +61,12 @@ function wrap (prefix, fn) { const wrapped = function () { if (!startCh.hasSubscribers) { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } const callbackIndex = findCallbackIndex(arguments) - if (callbackIndex < 0) return fn.apply(this, arguments) + if (callbackIndex < 0) return Reflect.apply(fn, this, arguments) const callbackResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -81,11 +81,11 @@ function wrap (prefix, fn) { errorCh.publish(error) } finishCh.publish(result) - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) })) try { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } catch (error) { error.stack // trigger getting the stack at the original throwing point errorCh.publish(error) @@ -171,10 +171,10 @@ addHook({ name: 'couchbase', file: 'lib/bucket.js', versions: ['^2.6.12'] }, Buc shimmer.wrap(Bucket.prototype, '_n1qlReq', _n1qlReq => function (host, q, adhoc, emitter) { if (!startCh.hasSubscribers) { - return _n1qlReq.apply(this, arguments) + return Reflect.apply(_n1qlReq, this, arguments) } - if (!emitter || !emitter.once) return _n1qlReq.apply(this, arguments) + if (!emitter || !emitter.once) return Reflect.apply(_n1qlReq, this, arguments) const n1qlQuery = getQueryResource(q) @@ -192,7 +192,7 @@ addHook({ name: 'couchbase', file: 'lib/bucket.js', versions: ['^2.6.12'] }, Buc })) try { - return _n1qlReq.apply(this, arguments) + return Reflect.apply(_n1qlReq, this, arguments) } catch (err) { err.stack // trigger getting the stack at the original throwing point errorCh.publish(err) @@ -215,7 +215,7 @@ addHook({ name: 'couchbase', file: 'lib/cluster.js', versions: ['^2.6.12'] }, Cl shimmer.wrap(Cluster.prototype, 'openBucket', openBucket => { return function () { - const bucket = openBucket.apply(this, arguments) + const bucket = Reflect.apply(openBucket, this, arguments) const hosts = this.dsnObj.hosts bucket._dd_hosts = hosts.map(hostAndPort => hostAndPort.join(':')).join(',') return bucket @@ -229,7 +229,7 @@ addHook({ name: 'couchbase', file: 'lib/cluster.js', versions: ['^2.6.12'] }, Cl addHook({ name: 'couchbase', file: 'lib/bucket.js', versions: ['^3.0.7', '^3.1.3'] }, Bucket => { shimmer.wrap(Bucket.prototype, 'collection', getCollection => { return function () { - const collection = getCollection.apply(this, arguments) + const collection = Reflect.apply(getCollection, this, arguments) const connStr = this._cluster._connStr collection._dd_connStr = connStr return collection @@ -269,7 +269,7 @@ addHook({ name: 'couchbase', file: 'dist/bucket.js', versions: ['>=3.2.2'] }, bu const Bucket = bucket.Bucket shimmer.wrap(Bucket.prototype, 'collection', getCollection => { return function () { - const collection = getCollection.apply(this, arguments) + const collection = Reflect.apply(getCollection, this, arguments) const connStr = this._cluster._connStr collection._dd_connStr = connStr return collection diff --git a/packages/datadog-instrumentations/src/crypto.js b/packages/datadog-instrumentations/src/crypto.js index 7c95614cee7..d76413bb430 100644 --- a/packages/datadog-instrumentations/src/crypto.js +++ b/packages/datadog-instrumentations/src/crypto.js @@ -26,7 +26,7 @@ function wrapCryptoMethod (channel) { const algorithm = arguments[0] channel.publish({ algorithm }) } - return cryptoMethod.apply(this, arguments) + return Reflect.apply(cryptoMethod, this, arguments) } } return wrapMethod diff --git a/packages/datadog-instrumentations/src/cucumber.js b/packages/datadog-instrumentations/src/cucumber.js index a97b8842938..5734345f67d 100644 --- a/packages/datadog-instrumentations/src/cucumber.js +++ b/packages/datadog-instrumentations/src/cucumber.js @@ -231,7 +231,7 @@ function wrapRun (pl, isLatestVersion) { shimmer.wrap(pl.prototype, 'run', run => function () { if (!testStartCh.hasSubscribers) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } let numAttempt = 0 @@ -292,7 +292,7 @@ function wrapRun (pl, isLatestVersion) { let promise asyncResource.runInAsyncScope(() => { - promise = run.apply(this, arguments) + promise = Reflect.apply(run, this, arguments) }) promise.finally(async () => { const result = this.getWorstStepResult() @@ -345,7 +345,7 @@ function wrapRun (pl, isLatestVersion) { }) shimmer.wrap(pl.prototype, 'runStep', runStep => function () { if (!testStepStartCh.hasSubscribers) { - return runStep.apply(this, arguments) + return Reflect.apply(runStep, this, arguments) } const testStep = arguments[0] let resource @@ -360,7 +360,7 @@ function wrapRun (pl, isLatestVersion) { return asyncResource.runInAsyncScope(() => { testStepStartCh.publish({ resource }) try { - const promise = runStep.apply(this, arguments) + const promise = Reflect.apply(runStep, this, arguments) promise.then((result) => { const { status, skipReason, errorMessage } = isLatestVersion @@ -405,7 +405,7 @@ function getCucumberOptions (adapterOrCoordinator) { function getWrappedStart (start, frameworkVersion, isParallel = false, isCoordinator = false) { return async function () { if (!libraryConfigurationCh.hasSubscribers) { - return start.apply(this, arguments) + return Reflect.apply(start, this, arguments) } const options = getCucumberOptions(this) @@ -505,7 +505,7 @@ function getWrappedStart (start, frameworkVersion, isParallel = false, isCoordin itrSkippedSuitesCh.publish({ skippedSuites, frameworkVersion }) } - const success = await start.apply(this, arguments) + const success = await Reflect.apply(start, this, arguments) let untestedCoverage if (getCodeCoverageCh.hasSubscribers) { @@ -587,7 +587,7 @@ function getWrappedRunTestCase (runTestCaseFunction, isNewerCucumberVersion = fa } // TODO: for >=11 we could use `runTestCaseResult` instead of accumulating results in `lastStatusByPickleId` - let runTestCaseResult = await runTestCaseFunction.apply(this, arguments) + let runTestCaseResult = await Reflect.apply(runTestCaseFunction, this, arguments) const testStatuses = lastStatusByPickleId.get(pickle.id) const lastTestStatus = testStatuses[testStatuses.length - 1] @@ -595,7 +595,7 @@ function getWrappedRunTestCase (runTestCaseFunction, isNewerCucumberVersion = fa if (isEarlyFlakeDetectionEnabled && lastTestStatus !== 'skip' && isNew) { for (let retryIndex = 0; retryIndex < earlyFlakeDetectionNumRetries; retryIndex++) { numRetriesByPickleId.set(pickle.id, retryIndex + 1) - runTestCaseResult = await runTestCaseFunction.apply(this, arguments) + runTestCaseResult = await Reflect.apply(runTestCaseFunction, this, arguments) } } let testStatus = lastTestStatus @@ -685,7 +685,7 @@ function getWrappedParseWorkerMessage (parseWorkerMessageFunction, isNewVersion) } if (!envelope) { - return parseWorkerMessageFunction.apply(this, arguments) + return Reflect.apply(parseWorkerMessageFunction, this, arguments) } let parsed = envelope @@ -694,7 +694,7 @@ function getWrappedParseWorkerMessage (parseWorkerMessageFunction, isNewVersion) parsed = JSON.parse(envelope) } catch (e) { // ignore errors and continue - return parseWorkerMessageFunction.apply(this, arguments) + return Reflect.apply(parseWorkerMessageFunction, this, arguments) } } let pickle @@ -717,7 +717,7 @@ function getWrappedParseWorkerMessage (parseWorkerMessageFunction, isNewVersion) } } - const parseWorkerResponse = parseWorkerMessageFunction.apply(this, arguments) + const parseWorkerResponse = Reflect.apply(parseWorkerMessageFunction, this, arguments) // after calling `parseWorkerMessageFunction`, the test status can already be read if (parsed.testCaseFinished) { @@ -876,7 +876,7 @@ addHook({ }, (eventDataCollectorPackage) => { shimmer.wrap(eventDataCollectorPackage.default.prototype, 'parseEnvelope', parseEnvelope => function () { eventDataCollector = this - return parseEnvelope.apply(this, arguments) + return Reflect.apply(parseEnvelope, this, arguments) }) return eventDataCollectorPackage }) @@ -902,7 +902,7 @@ addHook({ this.options.worldParameters._ddEarlyFlakeDetectionNumRetries = earlyFlakeDetectionNumRetries } - return startWorker.apply(this, arguments) + return Reflect.apply(startWorker, this, arguments) }) return adapterPackage }) @@ -919,7 +919,7 @@ addHook({ workerPackage.ChildProcessWorker.prototype, 'initialize', initialize => async function () { - await initialize.apply(this, arguments) + await Reflect.apply(initialize, this, arguments) isKnownTestsEnabled = !!this.options.worldParameters._ddKnownTests if (isKnownTestsEnabled) { knownTests = this.options.worldParameters._ddKnownTests diff --git a/packages/datadog-instrumentations/src/dns.js b/packages/datadog-instrumentations/src/dns.js index d37ebc44ee4..e6cffeddc74 100644 --- a/packages/datadog-instrumentations/src/dns.js +++ b/packages/datadog-instrumentations/src/dns.js @@ -59,7 +59,7 @@ function wrap (prefix, fn, expectedArgs, rrtype) { arguments.length < expectedArgs || typeof cb !== 'function' ) { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } const startArgs = Array.from(arguments) @@ -77,11 +77,11 @@ function wrap (prefix, fn, expectedArgs, rrtype) { errorCh.publish(error) } finishCh.publish(result) - cb.apply(this, arguments) + Reflect.apply(cb, this, arguments) })) try { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) // TODO deal with promise versions when we support `dns/promises` } catch (error) { error.stack // trigger getting the stack at the original throwing point diff --git a/packages/datadog-instrumentations/src/elasticsearch.js b/packages/datadog-instrumentations/src/elasticsearch.js index ef38cd8dd27..5a4c3205712 100644 --- a/packages/datadog-instrumentations/src/elasticsearch.js +++ b/packages/datadog-instrumentations/src/elasticsearch.js @@ -33,7 +33,7 @@ function createWrapGetConnection (name) { const connectCh = channel(`apm:${name}:query:connect`) return function wrapRequest (request) { return function () { - const connection = request.apply(this, arguments) + const connection = Reflect.apply(request, this, arguments) if (connectCh.hasSubscribers && connection && connection.url) { connectCh.publish(connection.url) } @@ -55,7 +55,7 @@ function createWrapSelect () { cb(err, connection) }) } - return request.apply(this, arguments) + return Reflect.apply(request, this, arguments) } } } @@ -68,10 +68,10 @@ function createWrapRequest (name) { return function wrapRequest (request) { return function (params, options, cb) { if (!startCh.hasSubscribers) { - return request.apply(this, arguments) + return Reflect.apply(request, this, arguments) } - if (!params) return request.apply(this, arguments) + if (!params) return Reflect.apply(request, this, arguments) const parentResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -88,11 +88,11 @@ function createWrapRequest (name) { arguments[lastIndex] = shimmer.wrapFunction(cb, cb => asyncResource.bind(function (error) { finish(params, error) - return cb.apply(null, arguments) + return Reflect.apply(cb, null, arguments) })) - return request.apply(this, arguments) + return Reflect.apply(request, this, arguments) } else { - const promise = request.apply(this, arguments) + const promise = Reflect.apply(request, this, arguments) if (promise && typeof promise.then === 'function') { const onResolve = asyncResource.bind(() => finish(params)) const onReject = asyncResource.bind(e => finish(params, e)) diff --git a/packages/datadog-instrumentations/src/express-mongo-sanitize.js b/packages/datadog-instrumentations/src/express-mongo-sanitize.js index 40d208fce4d..41cf8309e22 100644 --- a/packages/datadog-instrumentations/src/express-mongo-sanitize.js +++ b/packages/datadog-instrumentations/src/express-mongo-sanitize.js @@ -13,7 +13,7 @@ const propertiesToSanitize = ['body', 'params', 'headers', 'query'] addHook({ name: 'express-mongo-sanitize', versions: ['>=1.0.0'] }, expressMongoSanitize => { shimmer.wrap(expressMongoSanitize, 'sanitize', sanitize => function () { - const sanitizedObject = sanitize.apply(this, arguments) + const sanitizedObject = Reflect.apply(sanitize, this, arguments) if (sanitizeMethodFinished.hasSubscribers) { sanitizeMethodFinished.publish({ sanitizedObject }) @@ -23,11 +23,11 @@ addHook({ name: 'express-mongo-sanitize', versions: ['>=1.0.0'] }, expressMongoS }) return shimmer.wrapFunction(expressMongoSanitize, expressMongoSanitize => function () { - const middleware = expressMongoSanitize.apply(this, arguments) + const middleware = Reflect.apply(expressMongoSanitize, this, arguments) return shimmer.wrapFunction(middleware, middleware => function (req, res, next) { if (!sanitizeMiddlewareFinished.hasSubscribers) { - return middleware.apply(this, arguments) + return Reflect.apply(middleware, this, arguments) } const wrappedNext = shimmer.wrapFunction(next, next => function () { @@ -36,7 +36,7 @@ addHook({ name: 'express-mongo-sanitize', versions: ['>=1.0.0'] }, expressMongoS req }) - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) return middleware.call(this, req, res, wrappedNext) diff --git a/packages/datadog-instrumentations/src/express.js b/packages/datadog-instrumentations/src/express.js index 1b328ba4c13..bd3380a4863 100644 --- a/packages/datadog-instrumentations/src/express.js +++ b/packages/datadog-instrumentations/src/express.js @@ -13,7 +13,7 @@ function wrapHandle (handle) { handleChannel.publish({ req }) } - return handle.apply(this, arguments) + return Reflect.apply(handle, this, arguments) } } @@ -32,7 +32,7 @@ function wrapResponseJson (json) { responseJsonChannel.publish({ req: this.req, res: this, body: obj }) } - return json.apply(this, arguments) + return Reflect.apply(json, this, arguments) } } @@ -41,7 +41,7 @@ const responseRenderChannel = tracingChannel('datadog:express:response:render') function wrapResponseRender (render) { return function wrappedRender (view, options, callback) { if (!responseRenderChannel.start.hasSubscribers) { - return render.apply(this, arguments) + return Reflect.apply(render, this, arguments) } return responseRenderChannel.traceSync( @@ -94,7 +94,7 @@ function publishQueryParsedAndNext (req, res, next) { if (abortController.signal.aborted) return } - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } @@ -104,11 +104,11 @@ addHook({ file: 'lib/middleware/query.js' }, query => { return shimmer.wrapFunction(query, query => function () { - const queryMiddleware = query.apply(this, arguments) + const queryMiddleware = Reflect.apply(query, this, arguments) return shimmer.wrapFunction(queryMiddleware, queryMiddleware => function (req, res, next) { arguments[2] = publishQueryParsedAndNext(req, res, next) - return queryMiddleware.apply(this, arguments) + return Reflect.apply(queryMiddleware, this, arguments) }) }) }) @@ -131,7 +131,7 @@ function wrapProcessParamsMethod (requestPositionInArguments) { if (abortController.signal.aborted) return } - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } } } @@ -153,7 +153,7 @@ addHook({ name: 'express', file: ['lib/request.js'], versions: ['>=5.0.0'] }, re shimmer.wrap(requestDescriptor, 'get', function (originalGet) { return function wrappedGet () { - const query = originalGet.apply(this, arguments) + const query = Reflect.apply(originalGet, this, arguments) if (queryReadCh.hasSubscribers && query) { queryReadCh.publish({ query }) diff --git a/packages/datadog-instrumentations/src/fastify.js b/packages/datadog-instrumentations/src/fastify.js index 726e8284f92..7369178d46e 100644 --- a/packages/datadog-instrumentations/src/fastify.js +++ b/packages/datadog-instrumentations/src/fastify.js @@ -13,7 +13,7 @@ function wrapFastify (fastify, hasParsingEvents) { if (typeof fastify !== 'function') return fastify return function fastifyWithTrace () { - const app = fastify.apply(this, arguments) + const app = Reflect.apply(fastify, this, arguments) if (!app || typeof app.addHook !== 'function') return app @@ -39,7 +39,7 @@ function wrapAddHook (addHook) { return shimmer.wrapFunction(addHook, addHook => function addHookWithTrace (name, fn) { fn = arguments[arguments.length - 1] - if (typeof fn !== 'function') return addHook.apply(this, arguments) + if (typeof fn !== 'function') return Reflect.apply(addHook, this, arguments) arguments[arguments.length - 1] = shimmer.wrapFunction(fn, fn => function (request, reply, done) { const req = getReq(request) @@ -57,16 +57,16 @@ function wrapAddHook (addHook) { parsingResources.set(req, parsingResource) return parsingResource.runInAsyncScope(() => { - return done.apply(this, arguments) + return Reflect.apply(done, this, arguments) }) } else { - return done.apply(this, arguments) + return Reflect.apply(done, this, arguments) } } - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } else { - const promise = fn.apply(this, arguments) + const promise = Reflect.apply(fn, this, arguments) if (promise && typeof promise.catch === 'function') { return promise.catch(err => publishError(err, req)) @@ -79,7 +79,7 @@ function wrapAddHook (addHook) { } }) - return addHook.apply(this, arguments) + return Reflect.apply(addHook, this, arguments) }) } @@ -133,7 +133,7 @@ function wrapSend (send, req) { errorChannel.publish({ req, error }) } - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/find-my-way.js b/packages/datadog-instrumentations/src/find-my-way.js index 694412c96fe..6b1aa99e7eb 100644 --- a/packages/datadog-instrumentations/src/find-my-way.js +++ b/packages/datadog-instrumentations/src/find-my-way.js @@ -12,14 +12,14 @@ function wrapOn (on) { const wrapper = shimmer.wrapFunction(handler, handler => function (req) { routeChannel.publish({ req, route: path }) - return handler.apply(this, arguments) + return Reflect.apply(handler, this, arguments) }) if (typeof handler === 'function') { arguments[index] = wrapper } - return on.apply(this, arguments) + return Reflect.apply(on, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/fs.js b/packages/datadog-instrumentations/src/fs.js index 894c1b6ef33..3e68648bc14 100644 --- a/packages/datadog-instrumentations/src/fs.js +++ b/packages/datadog-instrumentations/src/fs.js @@ -176,7 +176,7 @@ function createWrapDirAsyncIterator () { } wrap(this, kDirReadPromisified, createWrapFunction('dir.', 'read')) wrap(this, kDirClosePromisified, createWrapFunction('dir.', 'close')) - return asyncIterator.apply(this, arguments) + return Reflect.apply(asyncIterator, this, arguments) } } } @@ -189,7 +189,7 @@ function wrapCreateStream (original) { const name = classes[original.name] return function (path, options) { - if (!startChannel.hasSubscribers) return original.apply(this, arguments) + if (!startChannel.hasSubscribers) return Reflect.apply(original, this, arguments) const innerResource = new AsyncResource('bound-anonymous-fn') const message = getMessage(name, ['path', 'options'], arguments) @@ -198,7 +198,7 @@ function wrapCreateStream (original) { startChannel.publish(message) try { - const stream = original.apply(this, arguments) + const stream = Reflect.apply(original, this, arguments) const onError = innerResource.bind(error => { errorChannel.publish(error) onFinish() @@ -238,13 +238,13 @@ function createWatchWrapFunction (override = '') { const method = name const operation = name return function () { - if (!startChannel.hasSubscribers) return original.apply(this, arguments) + if (!startChannel.hasSubscribers) return Reflect.apply(original, this, arguments) const message = getMessage(method, watchMethods[operation], arguments, this) const innerResource = new AsyncResource('bound-anonymous-fn') return innerResource.runInAsyncScope(() => { startChannel.publish(message) try { - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) finishChannel.publish() return result } catch (error) { @@ -264,7 +264,7 @@ function createWrapFunction (prefix = '', override = '') { const operation = name.match(/^(.+?)(Sync)?(\.native)?$/)[1] return function () { - if (!startChannel.hasSubscribers) return original.apply(this, arguments) + if (!startChannel.hasSubscribers) return Reflect.apply(original, this, arguments) const lastIndex = arguments.length - 1 const cb = typeof arguments[lastIndex] === 'function' && arguments[lastIndex] @@ -285,7 +285,7 @@ function createWrapFunction (prefix = '', override = '') { arguments[lastIndex] = shimmer.wrapFunction(cb, cb => innerResource.bind(function (e) { finish(e) - return outerResource.runInAsyncScope(() => cb.apply(this, arguments)) + return outerResource.runInAsyncScope(() => Reflect.apply(cb, this, arguments)) })) } @@ -308,7 +308,7 @@ function createWrapFunction (prefix = '', override = '') { } try { - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) if (cb) return result if (result && typeof result.then === 'function') { // TODO method open returning promise and filehandle prototype not initialized, initialize it diff --git a/packages/datadog-instrumentations/src/generic-pool.js b/packages/datadog-instrumentations/src/generic-pool.js index 067a9c7f2b3..700d42e160c 100644 --- a/packages/datadog-instrumentations/src/generic-pool.js +++ b/packages/datadog-instrumentations/src/generic-pool.js @@ -10,7 +10,7 @@ function createWrapAcquire () { arguments[0] = AsyncResource.bind(callback) } - return acquire.apply(this, arguments) + return Reflect.apply(acquire, this, arguments) } } } @@ -20,7 +20,7 @@ function createWrapPool () { if (typeof Pool !== 'function') return Pool return function PoolWithTrace (factory) { - const pool = Pool.apply(this, arguments) + const pool = Reflect.apply(Pool, this, arguments) if (pool && typeof pool.acquire === 'function') { shimmer.wrap(pool, 'acquire', createWrapAcquire()) diff --git a/packages/datadog-instrumentations/src/google-cloud-pubsub.js b/packages/datadog-instrumentations/src/google-cloud-pubsub.js index de1bc209f13..48d55073dc2 100644 --- a/packages/datadog-instrumentations/src/google-cloud-pubsub.js +++ b/packages/datadog-instrumentations/src/google-cloud-pubsub.js @@ -63,7 +63,7 @@ function wrapMethod (method) { const api = method.name return function (request) { - if (!requestStartCh.hasSubscribers) return method.apply(this, arguments) + if (!requestStartCh.hasSubscribers) return Reflect.apply(method, this, arguments) const innerAsyncResource = new AsyncResource('bound-anonymous-fn') @@ -83,12 +83,12 @@ function wrapMethod (method) { requestFinishCh.publish() - return outerAsyncResource.runInAsyncScope(() => cb.apply(this, arguments)) + return outerAsyncResource.runInAsyncScope(() => Reflect.apply(cb, this, arguments)) })) - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) } else { - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) .then( response => { requestFinishCh.publish() @@ -117,13 +117,13 @@ addHook({ name: '@google-cloud/pubsub', versions: ['>=1.2'] }, (obj) => { const Subscription = obj.Subscription shimmer.wrap(Subscription.prototype, 'emit', emit => function (eventName, message) { - if (eventName !== 'message' || !message) return emit.apply(this, arguments) + if (eventName !== 'message' || !message) return Reflect.apply(emit, this, arguments) const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { try { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } catch (err) { receiveErrorCh.publish(err) throw err @@ -141,19 +141,19 @@ addHook({ name: '@google-cloud/pubsub', versions: ['>=1.2'], file: 'build/src/le if (receiveStartCh.hasSubscribers) { receiveStartCh.publish({ message }) } - return dispense.apply(this, arguments) + return Reflect.apply(dispense, this, arguments) }) shimmer.wrap(LeaseManager.prototype, 'remove', remove => function (message) { receiveFinishCh.publish({ message }) - return remove.apply(this, arguments) + return Reflect.apply(remove, this, arguments) }) shimmer.wrap(LeaseManager.prototype, 'clear', clear => function () { for (const message of this._messages) { receiveFinishCh.publish({ message }) } - return clear.apply(this, arguments) + return Reflect.apply(clear, this, arguments) }) return obj diff --git a/packages/datadog-instrumentations/src/graphql.js b/packages/datadog-instrumentations/src/graphql.js index c776c4f4fa5..ac75af74e8b 100644 --- a/packages/datadog-instrumentations/src/graphql.js +++ b/packages/datadog-instrumentations/src/graphql.js @@ -89,7 +89,7 @@ function normalizePositional (args, defaultFieldResolver) { function wrapParse (parse) { return function (source) { if (!parseStartCh.hasSubscribers) { - return parse.apply(this, arguments) + return Reflect.apply(parse, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -98,7 +98,7 @@ function wrapParse (parse) { parseStartCh.publish() let document try { - document = parse.apply(this, arguments) + document = Reflect.apply(parse, this, arguments) const operation = getOperation(document) if (!operation) return document @@ -123,7 +123,7 @@ function wrapParse (parse) { function wrapValidate (validate) { return function (_schema, document, _rules, _typeInfo) { if (!validateStartCh.hasSubscribers) { - return validate.apply(this, arguments) + return Reflect.apply(validate, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -133,7 +133,7 @@ function wrapValidate (validate) { let errors try { - errors = validate.apply(this, arguments) + errors = Reflect.apply(validate, this, arguments) if (errors && errors[0]) { validateErrorCh.publish(errors && errors[0]) } @@ -155,7 +155,7 @@ function wrapExecute (execute) { const defaultFieldResolver = execute.defaultFieldResolver return function () { if (!startExecuteCh.hasSubscribers) { - return exe.apply(this, arguments) + return Reflect.apply(exe, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -168,7 +168,7 @@ function wrapExecute (execute) { const operation = getOperation(document, args.operationName) if (contexts.has(contextValue)) { - return exe.apply(this, arguments) + return Reflect.apply(exe, this, arguments) } if (schema) { @@ -206,11 +206,11 @@ function wrapResolve (resolve) { if (typeof resolve !== 'function' || patchedResolvers.has(resolve)) return resolve function resolveAsync (source, args, contextValue, info) { - if (!startResolveCh.hasSubscribers) return resolve.apply(this, arguments) + if (!startResolveCh.hasSubscribers) return Reflect.apply(resolve, this, arguments) const context = contexts.get(contextValue) - if (!context) return resolve.apply(this, arguments) + if (!context) return Reflect.apply(resolve, this, arguments) const field = assertField(context, info, args) diff --git a/packages/datadog-instrumentations/src/grpc/client.js b/packages/datadog-instrumentations/src/grpc/client.js index d52355c0dd6..b4f35219069 100644 --- a/packages/datadog-instrumentations/src/grpc/client.js +++ b/packages/datadog-instrumentations/src/grpc/client.js @@ -28,7 +28,7 @@ function createWrapMakeRequest (type, hasPeer = false) { function createWrapLoadPackageDefinition (hasPeer = false) { return function wrapLoadPackageDefinition (loadPackageDefinition) { return function (packageDef) { - const result = loadPackageDefinition.apply(this, arguments) + const result = Reflect.apply(loadPackageDefinition, this, arguments) if (!result) return result @@ -42,7 +42,7 @@ function createWrapLoadPackageDefinition (hasPeer = false) { function createWrapMakeClientConstructor (hasPeer = false) { return function wrapMakeClientConstructor (makeClientConstructor) { return function (methods) { - const ServiceClient = makeClientConstructor.apply(this, arguments) + const ServiceClient = Reflect.apply(makeClientConstructor, this, arguments) wrapClientConstructor(ServiceClient, methods, hasPeer) return ServiceClient } @@ -106,7 +106,7 @@ function wrapCallback (ctx, callback = () => { }) { } return asyncStartChannel.runStores(ctx, () => { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) // No async end channel needed }) }) @@ -139,7 +139,7 @@ function createWrapEmit (ctx, hasPeer = false) { } return emitChannel.runStores(ctx, () => { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) }) } } diff --git a/packages/datadog-instrumentations/src/grpc/server.js b/packages/datadog-instrumentations/src/grpc/server.js index 003dd0cb6c7..bb20e584a45 100644 --- a/packages/datadog-instrumentations/src/grpc/server.js +++ b/packages/datadog-instrumentations/src/grpc/server.js @@ -29,7 +29,7 @@ function wrapHandler (func, name) { } return function (call, callback) { - if (!isValid(this, arguments)) return func.apply(this, arguments) + if (!isValid(this, arguments)) return Reflect.apply(func, this, arguments) const metadata = call.metadata const type = types[this.type] @@ -56,12 +56,12 @@ function wrapHandler (func, name) { shimmer.wrap(call, 'emit', emit => { return function () { return emitChannel.runStores(ctx, () => { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) }) } }) - return func.apply(this, arguments) + return Reflect.apply(func, this, arguments) } catch (e) { ctx.error = e errorChannel.publish(ctx) @@ -77,7 +77,7 @@ function wrapRegister (register) { arguments[1] = wrapHandler(handler, name) } - return register.apply(this, arguments) + return Reflect.apply(register, this, arguments) } } @@ -105,7 +105,7 @@ function createWrapEmit (call, ctx, onCancel) { break } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } } } @@ -133,7 +133,7 @@ function wrapCallback (callback = () => {}, call, ctx, onCancel) { call.removeListener('cancelled', onCancel) return asyncStartChannel.runStores(ctx, () => { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) // No async end channel needed }) }) @@ -144,7 +144,7 @@ function wrapSendStatus (sendStatus, ctx) { ctx.status = status updateChannel.publish(ctx) - return sendStatus.apply(this, arguments) + return Reflect.apply(sendStatus, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/handlebars.js b/packages/datadog-instrumentations/src/handlebars.js index 333889db3c6..edb7fc2d046 100644 --- a/packages/datadog-instrumentations/src/handlebars.js +++ b/packages/datadog-instrumentations/src/handlebars.js @@ -12,7 +12,7 @@ function wrapCompile (compile) { handlebarsCompileCh.publish({ source }) } - return compile.apply(this, arguments) + return Reflect.apply(compile, this, arguments) } } @@ -22,7 +22,7 @@ function wrapRegisterPartial (registerPartial) { handlebarsRegisterPartialCh.publish({ partial }) } - return registerPartial.apply(this, arguments) + return Reflect.apply(registerPartial, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/hapi.js b/packages/datadog-instrumentations/src/hapi.js index afecf4c3284..c01f054c632 100644 --- a/packages/datadog-instrumentations/src/hapi.js +++ b/packages/datadog-instrumentations/src/hapi.js @@ -11,7 +11,7 @@ const hapiTracingChannel = tracingChannel('apm:hapi:extension') function wrapServer (server) { return function (options) { - const app = server.apply(this, arguments) + const app = Reflect.apply(server, this, arguments) if (!app) return app @@ -33,7 +33,7 @@ function wrapStart (start) { this.ext('onPreResponse', onPreResponse) } - return start.apply(this, arguments) + return Reflect.apply(start, this, arguments) }) } @@ -45,27 +45,27 @@ function wrapExt (ext) { arguments[1] = wrapExtension(method) } - return ext.apply(this, arguments) + return Reflect.apply(ext, this, arguments) }) } function wrapDispatch (dispatch) { return function (options) { - const handler = dispatch.apply(this, arguments) + const handler = Reflect.apply(dispatch, this, arguments) if (typeof handler !== 'function') return handler return function (req, res) { handleChannel.publish({ req, res }) - return handler.apply(this, arguments) + return Reflect.apply(handler, this, arguments) } } } function wrapRebuild (rebuild) { return function (event) { - const result = rebuild.apply(this, arguments) + const result = Reflect.apply(rebuild, this, arguments) if (this && Array.isArray(this._cycle)) { this._cycle = this._cycle.map(wrapHandler) @@ -95,10 +95,10 @@ function wrapHandler (handler) { return shimmer.wrapFunction(handler, handler => function (request, h) { const req = request && request.raw && request.raw.req - if (!req) return handler.apply(this, arguments) + if (!req) return Reflect.apply(handler, this, arguments) return hapiTracingChannel.traceSync(() => { - return handler.apply(this, arguments) + return Reflect.apply(handler, this, arguments) }) }) } diff --git a/packages/datadog-instrumentations/src/helpers/fetch.js b/packages/datadog-instrumentations/src/helpers/fetch.js index 0ae1f821e9e..9616699c350 100644 --- a/packages/datadog-instrumentations/src/helpers/fetch.js +++ b/packages/datadog-instrumentations/src/helpers/fetch.js @@ -5,7 +5,7 @@ exports.createWrapFetch = function createWrapFetch (Request, ch) { if (typeof fetch !== 'function') return fetch return function (input, init) { - if (!ch.start.hasSubscribers) return fetch.apply(this, arguments) + if (!ch.start.hasSubscribers) return Reflect.apply(fetch, this, arguments) if (input instanceof Request) { const ctx = { req: input } diff --git a/packages/datadog-instrumentations/src/helpers/promise.js b/packages/datadog-instrumentations/src/helpers/promise.js index 1ea8f6917e9..36fe19d7514 100644 --- a/packages/datadog-instrumentations/src/helpers/promise.js +++ b/packages/datadog-instrumentations/src/helpers/promise.js @@ -14,7 +14,7 @@ exports.wrapThen = function wrapThen (origThen) { arguments[2] = wrapCallback(ar, onProgress) } - return origThen.apply(this, arguments) + return Reflect.apply(origThen, this, arguments) } } @@ -23,7 +23,7 @@ function wrapCallback (ar, callback) { return function () { return ar.runInAsyncScope(() => { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) }) } } diff --git a/packages/datadog-instrumentations/src/http/client.js b/packages/datadog-instrumentations/src/http/client.js index 6ab01a34513..c6cc3646909 100644 --- a/packages/datadog-instrumentations/src/http/client.js +++ b/packages/datadog-instrumentations/src/http/client.js @@ -31,16 +31,16 @@ function patch (http, methodName) { function instrumentRequest (request) { return function () { if (!startChannel.hasSubscribers) { - return request.apply(this, arguments) + return Reflect.apply(request, this, arguments) } let args try { - args = normalizeArgs.apply(null, arguments) + args = Reflect.apply(normalizeArgs, null, arguments) } catch (e) { log.error('Error normalising http req arguments', e) - return request.apply(this, arguments) + return Reflect.apply(request, this, arguments) } const abortController = new AbortController() @@ -54,7 +54,7 @@ function patch (http, methodName) { if (callback) { callback = shimmer.wrapFunction(args.callback, cb => function () { return asyncStartChannel.runStores(ctx, () => { - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) }) }) } @@ -79,7 +79,7 @@ function patch (http, methodName) { let customRequestTimeout = false req.setTimeout = function () { customRequestTimeout = true - return setTimeout.apply(this, arguments) + return Reflect.apply(setTimeout, this, arguments) } req.emit = function (eventName, arg) { @@ -106,7 +106,7 @@ function patch (http, methodName) { finish() } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } if (abortController.signal.aborted) { diff --git a/packages/datadog-instrumentations/src/http/server.js b/packages/datadog-instrumentations/src/http/server.js index 0624c886787..d8c7a3dc0bf 100644 --- a/packages/datadog-instrumentations/src/http/server.js +++ b/packages/datadog-instrumentations/src/http/server.js @@ -43,7 +43,7 @@ addHook({ name: httpsNames }, http => { function wrapResponseEmit (emit) { return function (eventName, event) { if (!finishServerCh.hasSubscribers) { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } if (['finish', 'close'].includes(eventName) && !requestFinishedSet.has(this)) { @@ -51,13 +51,13 @@ function wrapResponseEmit (emit) { requestFinishedSet.add(this) } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } } function wrapEmit (emit) { return function (eventName, req, res) { if (!startServerCh.hasSubscribers) { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } if (eventName === 'request') { @@ -73,7 +73,7 @@ function wrapEmit (emit) { return this.listenerCount(eventName) > 0 } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } catch (err) { errorServerCh.publish(err) @@ -82,14 +82,14 @@ function wrapEmit (emit) { exitServerCh.publish({ req }) } } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } } function wrapWriteHead (writeHead) { return function wrappedWriteHead (statusCode, reason, obj) { if (!startWriteHeadCh.hasSubscribers) { - return writeHead.apply(this, arguments) + return Reflect.apply(writeHead, this, arguments) } const abortController = new AbortController() @@ -124,14 +124,14 @@ function wrapWriteHead (writeHead) { return this } - return writeHead.apply(this, arguments) + return Reflect.apply(writeHead, this, arguments) } } function wrapWrite (write) { return function wrappedWrite () { if (!startWriteHeadCh.hasSubscribers) { - return write.apply(this, arguments) + return Reflect.apply(write, this, arguments) } const abortController = new AbortController() @@ -150,14 +150,14 @@ function wrapWrite (write) { return true } - return write.apply(this, arguments) + return Reflect.apply(write, this, arguments) } } function wrapSetHeader (setHeader) { return function wrappedSetHeader (name, value) { if (!startSetHeaderCh.hasSubscribers && !finishSetHeaderCh.hasSubscribers) { - return setHeader.apply(this, arguments) + return Reflect.apply(setHeader, this, arguments) } if (startSetHeaderCh.hasSubscribers) { @@ -169,7 +169,7 @@ function wrapSetHeader (setHeader) { } } - const setHeaderResult = setHeader.apply(this, arguments) + const setHeaderResult = Reflect.apply(setHeader, this, arguments) if (finishSetHeaderCh.hasSubscribers) { finishSetHeaderCh.publish({ name, value, res: this }) @@ -182,7 +182,7 @@ function wrapSetHeader (setHeader) { function wrapAppendOrRemoveHeader (originalMethod) { return function wrappedAppendOrRemoveHeader () { if (!startSetHeaderCh.hasSubscribers) { - return originalMethod.apply(this, arguments) + return Reflect.apply(originalMethod, this, arguments) } const abortController = new AbortController() @@ -192,14 +192,14 @@ function wrapAppendOrRemoveHeader (originalMethod) { return this } - return originalMethod.apply(this, arguments) + return Reflect.apply(originalMethod, this, arguments) } } function wrapEnd (end) { return function wrappedEnd () { if (!startWriteHeadCh.hasSubscribers) { - return end.apply(this, arguments) + return Reflect.apply(end, this, arguments) } const abortController = new AbortController() @@ -218,6 +218,6 @@ function wrapEnd (end) { return this } - return end.apply(this, arguments) + return Reflect.apply(end, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/http2/client.js b/packages/datadog-instrumentations/src/http2/client.js index 651c9ed6edd..9bcf58e1920 100644 --- a/packages/datadog-instrumentations/src/http2/client.js +++ b/packages/datadog-instrumentations/src/http2/client.js @@ -20,7 +20,7 @@ function createWrapEmit (ctx) { return asyncStartChannel.runStores(ctx, () => { try { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } finally { asyncEndChannel.publish(ctx) } @@ -32,13 +32,13 @@ function createWrapEmit (ctx) { function createWrapRequest (authority, options) { return function wrapRequest (request) { return function (headers) { - if (!startChannel.hasSubscribers) return request.apply(this, arguments) + if (!startChannel.hasSubscribers) return Reflect.apply(request, this, arguments) const ctx = { headers, authority, options } return startChannel.runStores(ctx, () => { try { - const req = request.apply(this, arguments) + const req = Reflect.apply(request, this, arguments) shimmer.wrap(req, 'emit', createWrapEmit(ctx)) @@ -60,7 +60,7 @@ function wrapConnect (connect) { if (connectChannel.hasSubscribers) { connectChannel.publish({ authority }) } - const session = connect.apply(this, arguments) + const session = Reflect.apply(connect, this, arguments) shimmer.wrap(session, 'request', createWrapRequest(authority, options)) diff --git a/packages/datadog-instrumentations/src/http2/server.js b/packages/datadog-instrumentations/src/http2/server.js index 07bfa11e453..5c3ce1e3208 100644 --- a/packages/datadog-instrumentations/src/http2/server.js +++ b/packages/datadog-instrumentations/src/http2/server.js @@ -38,14 +38,14 @@ function wrapResponseEmit (emit) { finishServerCh.publish({ req: this.req }) } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) }) } } function wrapEmit (emit) { return function (eventName, req, res) { if (!startServerCh.hasSubscribers) { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } if (eventName === 'request') { @@ -58,7 +58,7 @@ function wrapEmit (emit) { shimmer.wrap(res, 'emit', wrapResponseEmit) try { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } catch (err) { errorServerCh.publish(err) @@ -66,6 +66,6 @@ function wrapEmit (emit) { } }) } - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/ioredis.js b/packages/datadog-instrumentations/src/ioredis.js index 26f104d8e2a..2debfdaa26c 100644 --- a/packages/datadog-instrumentations/src/ioredis.js +++ b/packages/datadog-instrumentations/src/ioredis.js @@ -13,9 +13,9 @@ const errorCh = channel('apm:ioredis:command:error') addHook({ name: 'ioredis', versions: ['>=2'] }, Redis => { shimmer.wrap(Redis.prototype, 'sendCommand', sendCommand => function (command, stream) { - if (!startCh.hasSubscribers) return sendCommand.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(sendCommand, this, arguments) - if (!command || !command.promise) return sendCommand.apply(this, arguments) + if (!command || !command.promise) return Reflect.apply(sendCommand, this, arguments) const options = this.options || {} const connectionName = options.connectionName @@ -32,7 +32,7 @@ addHook({ name: 'ioredis', versions: ['>=2'] }, Redis => { command.promise.then(onResolve, onReject) try { - return sendCommand.apply(this, arguments) + return Reflect.apply(sendCommand, this, arguments) } catch (err) { errorCh.publish(err) diff --git a/packages/datadog-instrumentations/src/jest.js b/packages/datadog-instrumentations/src/jest.js index da31b18e6d1..8301d8d0486 100644 --- a/packages/datadog-instrumentations/src/jest.js +++ b/packages/datadog-instrumentations/src/jest.js @@ -245,11 +245,11 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) { if (this.global.test) { shimmer.wrap(this.global.test, 'each', each => function () { const testParameters = getFormattedJestTestParameters(arguments) - const eachBind = each.apply(this, arguments) + const eachBind = Reflect.apply(each, this, arguments) return function () { const [testName] = arguments setNameToParams(testName, testParameters) - return eachBind.apply(this, arguments) + return Reflect.apply(eachBind, this, arguments) } }) } @@ -441,14 +441,14 @@ addHook({ function getWrappedScheduleTests (scheduleTests, frameworkVersion) { return async function (tests) { if (!isSuitesSkippingEnabled || hasFilteredSkippableSuites) { - return scheduleTests.apply(this, arguments) + return Reflect.apply(scheduleTests, this, arguments) } const [test] = tests const rootDir = test?.context?.config?.rootDir arguments[0] = applySuiteSkipping(tests, rootDir, frameworkVersion) - return scheduleTests.apply(this, arguments) + return Reflect.apply(scheduleTests, this, arguments) } } @@ -460,10 +460,10 @@ addHook({ const oldCreateTestScheduler = testSchedulerPackage.createTestScheduler const newCreateTestScheduler = async function () { if (!isSuitesSkippingEnabled || hasFilteredSkippableSuites) { - return oldCreateTestScheduler.apply(this, arguments) + return Reflect.apply(oldCreateTestScheduler, this, arguments) } // If suite skipping is enabled and has not filtered skippable suites yet, we'll attempt to do it - const scheduler = await oldCreateTestScheduler.apply(this, arguments) + const scheduler = await Reflect.apply(oldCreateTestScheduler, this, arguments) shimmer.wrap(scheduler, 'scheduleTests', scheduleTests => getWrappedScheduleTests(scheduleTests, frameworkVersion)) return scheduler } @@ -488,7 +488,7 @@ addHook({ versions: ['>=28'] }, (sequencerPackage, frameworkVersion) => { shimmer.wrap(sequencerPackage.default.prototype, 'shard', shard => function () { - const shardedTests = shard.apply(this, arguments) + const shardedTests = Reflect.apply(shard, this, arguments) if (!shardedTests.length || !isSuitesSkippingEnabled || !skippableSuites.length) { return shardedTests @@ -508,7 +508,7 @@ function cliWrapper (cli, jestVersion) { onDone = resolve }) if (!libraryConfigurationCh.hasSubscribers) { - return runCLI.apply(this, arguments) + return Reflect.apply(runCLI, this, arguments) } sessionAsyncResource.runInAsyncScope(() => { @@ -596,7 +596,7 @@ function cliWrapper (cli, jestVersion) { testSessionStartCh.publish({ command: `jest ${processArgv}`, frameworkVersion: jestVersion }) }) - const result = await runCLI.apply(this, arguments) + const result = await Reflect.apply(runCLI, this, arguments) const { results: { @@ -747,7 +747,7 @@ function coverageReporterWrapper (coverageReporter) { if (isSuitesSkippingEnabled && !isUserCodeCoverageEnabled) { return Promise.resolve() } - return addUntestedFiles.apply(this, arguments) + return Reflect.apply(addUntestedFiles, this, arguments) }) return coverageReporter @@ -776,7 +776,7 @@ function jestAdapterWrapper (jestAdapter, jestVersion) { const newAdapter = shimmer.wrapFunction(adapter, adapter => function () { const environment = arguments[2] if (!environment) { - return adapter.apply(this, arguments) + return Reflect.apply(adapter, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { @@ -787,7 +787,7 @@ function jestAdapterWrapper (jestAdapter, jestVersion) { displayName: environment.displayName, frameworkVersion: jestVersion }) - return adapter.apply(this, arguments).then(suiteResults => { + return Reflect.apply(adapter, this, arguments).then(suiteResults => { const { numFailingTests, skipped, failureMessage: errorMessage } = suiteResults let status = 'pass' if (skipped) { @@ -875,7 +875,7 @@ function configureTestEnvironment (readConfigsResult) { function jestConfigAsyncWrapper (jestConfig) { shimmer.wrap(jestConfig, 'readConfigs', readConfigs => async function () { - const readConfigsResult = await readConfigs.apply(this, arguments) + const readConfigsResult = await Reflect.apply(readConfigs, this, arguments) configureTestEnvironment(readConfigsResult) return readConfigsResult }) @@ -884,7 +884,7 @@ function jestConfigAsyncWrapper (jestConfig) { function jestConfigSyncWrapper (jestConfig) { shimmer.wrap(jestConfig, 'readConfigs', readConfigs => function () { - const readConfigsResult = readConfigs.apply(this, arguments) + const readConfigsResult = Reflect.apply(readConfigs, this, arguments) configureTestEnvironment(readConfigsResult) return readConfigsResult }) @@ -925,7 +925,7 @@ addHook({ arguments[0] = restOfConfig - return originalCreateScriptTransformer.apply(this, arguments) + return Reflect.apply(originalCreateScriptTransformer, this, arguments) } return transformPackage @@ -942,7 +942,7 @@ addHook({ const SearchSource = searchSourcePackage.default ? searchSourcePackage.default : searchSourcePackage shimmer.wrap(SearchSource.prototype, 'getTestPaths', getTestPaths => async function () { - const testPaths = await getTestPaths.apply(this, arguments) + const testPaths = await Reflect.apply(getTestPaths, this, arguments) const [{ rootDir, shard }] = arguments if (isKnownTestsEnabled) { @@ -1022,7 +1022,7 @@ addHook({ // To bypass jest's own require engine return this._requireCoreModule(moduleName) } - return requireModuleOrMock.apply(this, arguments) + return Reflect.apply(requireModuleOrMock, this, arguments) }) return runtimePackage @@ -1042,7 +1042,7 @@ addHook({ const ChildProcessWorker = childProcessWorker.default shimmer.wrap(ChildProcessWorker.prototype, 'send', send => function (request) { if (!isKnownTestsEnabled && !isQuarantinedTestsEnabled) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const [type] = request // eslint-disable-next-line @@ -1053,10 +1053,10 @@ addHook({ // This way the suite only knows about the tests that are part of it. const args = request[request.length - 1] if (args.length > 1) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } if (!args[0]?.config) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const [{ globalConfig, config, path: testSuiteAbsolutePath }] = args const testSuite = getTestSuitePath(testSuiteAbsolutePath, globalConfig.rootDir || process.cwd()) @@ -1074,7 +1074,7 @@ addHook({ } } - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) }) shimmer.wrap(ChildProcessWorker.prototype, '_onMessage', _onMessage => function () { const [code, data] = arguments[0] @@ -1096,7 +1096,7 @@ addHook({ }) return } - return _onMessage.apply(this, arguments) + return Reflect.apply(_onMessage, this, arguments) }) return childProcessWorker }) diff --git a/packages/datadog-instrumentations/src/kafkajs.js b/packages/datadog-instrumentations/src/kafkajs.js index e75c03e7e64..158577f0816 100644 --- a/packages/datadog-instrumentations/src/kafkajs.js +++ b/packages/datadog-instrumentations/src/kafkajs.js @@ -48,7 +48,7 @@ addHook({ name: 'kafkajs', file: 'src/index.js', versions: ['>=1.4'] }, (BaseKaf } shimmer.wrap(Kafka.prototype, 'producer', createProducer => function () { - const producer = createProducer.apply(this, arguments) + const producer = Reflect.apply(createProducer, this, arguments) const send = producer.send const bootstrapServers = this._brokers @@ -60,7 +60,7 @@ addHook({ name: 'kafkajs', file: 'src/index.js', versions: ['>=1.4'] }, (BaseKaf return innerAsyncResource.runInAsyncScope(() => { if (!producerStartCh.hasSubscribers) { - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } try { @@ -72,7 +72,7 @@ addHook({ name: 'kafkajs', file: 'src/index.js', versions: ['>=1.4'] }, (BaseKaf } producerStartCh.publish({ topic, messages, bootstrapServers, clusterId }) - const result = send.apply(this, arguments) + const result = Reflect.apply(send, this, arguments) result.then( innerAsyncResource.bind(res => { @@ -111,7 +111,7 @@ addHook({ name: 'kafkajs', file: 'src/index.js', versions: ['>=1.4'] }, (BaseKaf shimmer.wrap(Kafka.prototype, 'consumer', createConsumer => function () { if (!consumerStartCh.hasSubscribers) { - return createConsumer.apply(this, arguments) + return Reflect.apply(createConsumer, this, arguments) } const kafkaClusterIdPromise = getKafkaClusterId(this) @@ -127,7 +127,7 @@ addHook({ name: 'kafkajs', file: 'src/index.js', versions: ['>=1.4'] }, (BaseKaf return { topic, partition, messages, groupId, clusterId } } - const consumer = createConsumer.apply(this, arguments) + const consumer = Reflect.apply(createConsumer, this, arguments) consumer.on(consumer.events.COMMIT_OFFSETS, commitsFromEvent) diff --git a/packages/datadog-instrumentations/src/knex.js b/packages/datadog-instrumentations/src/knex.js index 43d5db38181..fd62d915acc 100644 --- a/packages/datadog-instrumentations/src/knex.js +++ b/packages/datadog-instrumentations/src/knex.js @@ -29,14 +29,14 @@ addHook({ }, Knex => { shimmer.wrap(Knex.Client.prototype, 'raw', raw => function () { if (!startRawQueryCh.hasSubscribers) { - return raw.apply(this, arguments) + return Reflect.apply(raw, this, arguments) } const sql = arguments[0] // Skip query done by Knex to get the value used for undefined if (sql === 'DEFAULT') { - return raw.apply(this, arguments) + return Reflect.apply(raw, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -48,17 +48,17 @@ addHook({ return asyncResource.runInAsyncScope(() => { startRawQueryCh.publish({ sql, dialect: this.dialect }) - const rawResult = raw.apply(this, arguments) + const rawResult = Reflect.apply(raw, this, arguments) shimmer.wrap(rawResult, 'then', originalThen => function () { return asyncResource.runInAsyncScope(() => { arguments[0] = wrapCallbackWithFinish(arguments[0], finish) if (arguments[1]) arguments[1] = wrapCallbackWithFinish(arguments[1], finish) - const originalThenResult = originalThen.apply(this, arguments) + const originalThenResult = Reflect.apply(originalThen, this, arguments) shimmer.wrap(originalThenResult, 'catch', originalCatch => function () { arguments[0] = wrapCallbackWithFinish(arguments[0], finish) - return originalCatch.apply(this, arguments) + return Reflect.apply(originalCatch, this, arguments) }) return originalThenResult @@ -68,7 +68,7 @@ addHook({ shimmer.wrap(rawResult, 'asCallback', originalAsCallback => function () { return asyncResource.runInAsyncScope(() => { arguments[0] = wrapCallbackWithFinish(arguments[0], finish) - return originalAsCallback.apply(this, arguments) + return Reflect.apply(originalAsCallback, this, arguments) }) }) @@ -83,6 +83,6 @@ function wrapCallbackWithFinish (callback, finish) { return shimmer.wrapFunction(callback, callback => function () { finish() - callback.apply(this, arguments) + Reflect.apply(callback, this, arguments) }) } diff --git a/packages/datadog-instrumentations/src/koa.js b/packages/datadog-instrumentations/src/koa.js index f139eb1c494..0e3f0c9fca7 100644 --- a/packages/datadog-instrumentations/src/koa.js +++ b/packages/datadog-instrumentations/src/koa.js @@ -15,21 +15,21 @@ const originals = new WeakMap() function wrapCallback (callback) { return function callbackWithTrace () { - const handleRequest = callback.apply(this, arguments) + const handleRequest = Reflect.apply(callback, this, arguments) if (typeof handleRequest !== 'function') return handleRequest return function handleRequestWithTrace (req, res) { handleChannel.publish({ req, res }) - return handleRequest.apply(this, arguments) + return Reflect.apply(handleRequest, this, arguments) } } } function wrapUse (use) { return function useWithTrace () { - const result = use.apply(this, arguments) + const result = Reflect.apply(use, this, arguments) if (!Array.isArray(this.middleware)) return result @@ -43,7 +43,7 @@ function wrapUse (use) { function wrapRegister (register) { return function registerWithTrace (path, methods, middleware, opts) { - const route = register.apply(this, arguments) + const route = Reflect.apply(register, this, arguments) if (!Array.isArray(path) && route && Array.isArray(route.stack)) { wrapStack(route) @@ -55,7 +55,7 @@ function wrapRegister (register) { function wrapRouterUse (use) { return function useWithTrace () { - const router = use.apply(this, arguments) + const router = Reflect.apply(use, this, arguments) router.stack.forEach(wrapStack) @@ -85,7 +85,7 @@ function wrapMiddleware (fn, layer) { const name = fn.name return shimmer.wrapFunction(fn, fn => function (ctx, next) { - if (!ctx || !enterChannel.hasSubscribers) return fn.apply(this, arguments) + if (!ctx || !enterChannel.hasSubscribers) return Reflect.apply(fn, this, arguments) const req = ctx.req @@ -99,7 +99,7 @@ function wrapMiddleware (fn, layer) { } try { - const result = fn.apply(this, arguments) + const result = Reflect.apply(fn, this, arguments) if (result && typeof result.then === 'function') { return result.then( @@ -145,7 +145,7 @@ function wrapNext (req, next) { return shimmer.wrapFunction(next, next => function () { nextChannel.publish({ req }) - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } diff --git a/packages/datadog-instrumentations/src/langchain.js b/packages/datadog-instrumentations/src/langchain.js index 6b9321c5ab5..561d9447c2d 100644 --- a/packages/datadog-instrumentations/src/langchain.js +++ b/packages/datadog-instrumentations/src/langchain.js @@ -10,7 +10,7 @@ const invokeTracingChannel = tracingChannel('apm:langchain:invoke') function wrapLangChainPromise (fn, type, namespace = []) { return function () { if (!invokeTracingChannel.start.hasSubscribers) { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } // Runnable interfaces have an `lc_namespace` property diff --git a/packages/datadog-instrumentations/src/ldapjs.js b/packages/datadog-instrumentations/src/ldapjs.js index da70642aee9..842655be96d 100644 --- a/packages/datadog-instrumentations/src/ldapjs.js +++ b/packages/datadog-instrumentations/src/ldapjs.js @@ -35,7 +35,7 @@ function wrapEmitter (corkedEmitter) { } arguments[1] = bindedFn } - return on.apply(this, arguments) + return Reflect.apply(on, this, arguments) } shimmer.wrap(corkedEmitter, 'on', addListener) shimmer.wrap(corkedEmitter, 'addListener', addListener) @@ -47,7 +47,7 @@ function wrapEmitter (corkedEmitter) { arguments[1] = emitterOn } } - return off.apply(this, arguments) + return Reflect.apply(off, this, arguments) } shimmer.wrap(corkedEmitter, 'off', removeListener) shimmer.wrap(corkedEmitter, 'removeListener', removeListener) @@ -69,7 +69,7 @@ addHook({ name: 'ldapjs', versions: ['>=2'] }, ldapjs => { ldapSearchCh.publish({ base, filter }) } - return search.apply(this, arguments) + return Reflect.apply(search, this, arguments) }) shimmer.wrap(ldapjs.Client.prototype, '_send', _send => function () { @@ -81,11 +81,11 @@ addHook({ name: 'ldapjs', versions: ['>=2'] }, ldapjs => { if (corkedEmitter !== null && typeof corkedEmitter === 'object' && typeof corkedEmitter.on === 'function') { wrapEmitter(corkedEmitter) } - callback.apply(this, arguments) + Reflect.apply(callback, this, arguments) }) } - return _send.apply(this, arguments) + return Reflect.apply(_send, this, arguments) }) shimmer.wrap(ldapjs.Client.prototype, 'bind', bind => function (dn, password, controls, callback) { @@ -95,7 +95,7 @@ addHook({ name: 'ldapjs', versions: ['>=2'] }, ldapjs => { arguments[3] = AsyncResource.bind(callback) } - return bind.apply(this, arguments) + return Reflect.apply(bind, this, arguments) }) return ldapjs diff --git a/packages/datadog-instrumentations/src/limitd-client.js b/packages/datadog-instrumentations/src/limitd-client.js index 9c974e587b8..3f3054a0834 100644 --- a/packages/datadog-instrumentations/src/limitd-client.js +++ b/packages/datadog-instrumentations/src/limitd-client.js @@ -7,7 +7,7 @@ function wrapRequest (original) { return function () { const id = arguments.length - 1 arguments[id] = AsyncResource.bind(arguments[id]) - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/lodash.js b/packages/datadog-instrumentations/src/lodash.js index 2ac9a1afd64..99865c7ef3b 100644 --- a/packages/datadog-instrumentations/src/lodash.js +++ b/packages/datadog-instrumentations/src/lodash.js @@ -15,10 +15,10 @@ addHook({ name: 'lodash', versions: ['>=4'] }, lodash => { lodashFn => { return function () { if (!lodashOperationCh.hasSubscribers) { - return lodashFn.apply(this, arguments) + return Reflect.apply(lodashFn, this, arguments) } - const result = lodashFn.apply(this, arguments) + const result = Reflect.apply(lodashFn, this, arguments) const message = { operation: lodashFn.name, arguments, result } lodashOperationCh.publish(message) diff --git a/packages/datadog-instrumentations/src/mariadb.js b/packages/datadog-instrumentations/src/mariadb.js index 9a6891bfa20..b9d452fe1f8 100644 --- a/packages/datadog-instrumentations/src/mariadb.js +++ b/packages/datadog-instrumentations/src/mariadb.js @@ -12,7 +12,7 @@ const unskipCh = channel('apm:mariadb:pool:unskip') function wrapCommandStart (start, callbackResource) { return shimmer.wrapFunction(start, start => function () { - if (!startCh.hasSubscribers) return start.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(start, this, arguments) const resolve = callbackResource.bind(this.resolve) const reject = callbackResource.bind(this.reject) @@ -25,7 +25,7 @@ function wrapCommandStart (start, callbackResource) { finishCh.publish() }) - return resolve.apply(this, arguments) + return Reflect.apply(resolve, this, arguments) } }) @@ -36,13 +36,13 @@ function wrapCommandStart (start, callbackResource) { finishCh.publish() }) - return reject.apply(this, arguments) + return Reflect.apply(reject, this, arguments) } }) return asyncResource.runInAsyncScope(() => { startCh.publish({ sql: this.sql, conf: this.opts }) - return start.apply(this, arguments) + return Reflect.apply(start, this, arguments) }) }) } @@ -64,14 +64,14 @@ function wrapCommand (Command) { function createWrapQuery (options) { return function wrapQuery (query) { return function (sql) { - if (!startCh.hasSubscribers) return query.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(query, this, arguments) const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { startCh.publish({ sql, conf: options }) - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) .then(result => { finishCh.publish() return result @@ -88,7 +88,7 @@ function createWrapQuery (options) { function createWrapQueryCallback (options) { return function wrapQuery (query) { return function (sql) { - if (!startCh.hasSubscribers) return query.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(query, this, arguments) const cb = arguments[arguments.length - 1] const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -106,14 +106,14 @@ function createWrapQueryCallback (options) { finishCh.publish() if (typeof cb === 'function') { - return callbackResource.runInAsyncScope(() => cb.apply(this, arguments)) + return callbackResource.runInAsyncScope(() => Reflect.apply(cb, this, arguments)) } })) return asyncResource.runInAsyncScope(() => { startCh.publish({ sql, conf: options }) - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) }, 'bound-anonymous-fn') } } @@ -121,7 +121,7 @@ function createWrapQueryCallback (options) { function wrapConnection (promiseMethod, Connection) { return function (options) { - Connection.apply(this, arguments) + Reflect.apply(Connection, this, arguments) shimmer.wrap(this, promiseMethod, createWrapQuery(options)) shimmer.wrap(this, '_queryCallback', createWrapQueryCallback(options)) @@ -133,7 +133,7 @@ function wrapPoolBase (PoolBase) { arguments[1] = wrapPoolMethod(processTask) arguments[2] = wrapPoolMethod(createConnectionPool) - PoolBase.apply(this, arguments) + Reflect.apply(PoolBase, this, arguments) shimmer.wrap(this, 'query', createWrapQuery(options.connOptions)) } @@ -146,7 +146,7 @@ function wrapPoolMethod (createConnection) { return function () { skipCh.publish() try { - return createConnection.apply(this, arguments) + return Reflect.apply(createConnection, this, arguments) } finally { unskipCh.publish() } diff --git a/packages/datadog-instrumentations/src/memcached.js b/packages/datadog-instrumentations/src/memcached.js index 672f5a6a6e4..7be544d5d31 100644 --- a/packages/datadog-instrumentations/src/memcached.js +++ b/packages/datadog-instrumentations/src/memcached.js @@ -14,7 +14,7 @@ addHook({ name: 'memcached', versions: ['>=2.2'] }, Memcached => { shimmer.wrap(Memcached.prototype, 'command', command => function (queryCompiler, server) { if (!startCh.hasSubscribers) { - return command.apply(this, arguments) + return Reflect.apply(command, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') @@ -23,7 +23,7 @@ addHook({ name: 'memcached', versions: ['>=2.2'] }, Memcached => { const client = this const wrappedQueryCompiler = asyncResource.bind(function () { - const query = queryCompiler.apply(this, arguments) + const query = Reflect.apply(queryCompiler, this, arguments) const callback = callbackResource.bind(query.callback) query.callback = shimmer.wrapFunction(callback, callback => asyncResource.bind(function (err) { @@ -32,7 +32,7 @@ addHook({ name: 'memcached', versions: ['>=2.2'] }, Memcached => { } finishCh.publish() - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) })) startCh.publish({ client, server, query }) @@ -42,7 +42,7 @@ addHook({ name: 'memcached', versions: ['>=2.2'] }, Memcached => { return asyncResource.runInAsyncScope(() => { arguments[0] = wrappedQueryCompiler - const result = command.apply(this, arguments) + const result = Reflect.apply(command, this, arguments) return result }) diff --git a/packages/datadog-instrumentations/src/microgateway-core.js b/packages/datadog-instrumentations/src/microgateway-core.js index f96a769ae85..0e91a747187 100644 --- a/packages/datadog-instrumentations/src/microgateway-core.js +++ b/packages/datadog-instrumentations/src/microgateway-core.js @@ -15,7 +15,7 @@ const requestResources = new WeakMap() function wrapConfigProxyFactory (configProxyFactory) { return function () { - const configProxy = configProxyFactory.apply(this, arguments) + const configProxy = Reflect.apply(configProxyFactory, this, arguments) return function (req, res, next) { const requestResource = new AsyncResource('bound-anonymous-fn') @@ -24,19 +24,19 @@ function wrapConfigProxyFactory (configProxyFactory) { handleChannel.publish({ req, res }) - return configProxy.apply(this, arguments) + return Reflect.apply(configProxy, this, arguments) } } } function wrapPluginsFactory (pluginsFactory) { return function (plugins) { - const pluginsMiddleware = pluginsFactory.apply(this, arguments) + const pluginsMiddleware = Reflect.apply(pluginsFactory, this, arguments) return function pluginsMiddlewareWithTrace (req, res, next) { arguments[2] = wrapNext(req, res, next) - return pluginsMiddleware.apply(this, arguments) + return Reflect.apply(pluginsMiddleware, this, arguments) } } } @@ -55,7 +55,7 @@ function wrapNext (req, res, next) { } }) - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } diff --git a/packages/datadog-instrumentations/src/mocha/common.js b/packages/datadog-instrumentations/src/mocha/common.js index c25ab2fdb21..a6432d954ad 100644 --- a/packages/datadog-instrumentations/src/mocha/common.js +++ b/packages/datadog-instrumentations/src/mocha/common.js @@ -17,11 +17,11 @@ addHook({ return shimmer.wrapFunction(mochaEach, mochaEach => function () { const [params] = arguments - const { it, ...rest } = mochaEach.apply(this, arguments) + const { it, ...rest } = Reflect.apply(mochaEach, this, arguments) return { it: function (title) { parameterizedTestCh.publish({ title, params }) - it.apply(this, arguments) + Reflect.apply(it, this, arguments) }, ...rest } @@ -42,7 +42,7 @@ addHook({ startLine = testCallSite.getLineNumber() testToStartLine.set(test, startLine) } - return addTest.apply(this, arguments) + return Reflect.apply(addTest, this, arguments) }) return Suite }) diff --git a/packages/datadog-instrumentations/src/mocha/main.js b/packages/datadog-instrumentations/src/mocha/main.js index 143935da3fb..b461a6a54a7 100644 --- a/packages/datadog-instrumentations/src/mocha/main.js +++ b/packages/datadog-instrumentations/src/mocha/main.js @@ -297,14 +297,14 @@ addHook({ shimmer.wrap(Mocha.prototype, 'run', run => function () { // Workers do not need to request any data, just run the tests if (!testStartCh.hasSubscribers || process.env.MOCHA_WORKER_ID || this.options.parallel) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } // `options.delay` does not work in parallel mode, so we can't delay the execution this way // This needs to be both here and in `runMocha` hook. Read the comment in `runMocha` hook for more info. this.options.delay = true - const runner = run.apply(this, arguments) + const runner = Reflect.apply(run, this, arguments) this.files.forEach(path => { const isUnskippable = isMarkedAsUnskippable({ path }) @@ -351,7 +351,7 @@ addHook({ }, (run) => { shimmer.wrap(run, 'runMocha', runMocha => async function () { if (!testStartCh.hasSubscribers) { - return runMocha.apply(this, arguments) + return Reflect.apply(runMocha, this, arguments) } const mocha = arguments[0] @@ -367,7 +367,7 @@ addHook({ mocha.options.delay = true } - return runMocha.apply(this, arguments) + return Reflect.apply(runMocha, this, arguments) }) return run }) @@ -387,7 +387,7 @@ addHook({ shimmer.wrap(Runner.prototype, 'run', run => function () { if (!testStartCh.hasSubscribers) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } const { suitesByTestFile, numSuitesByTestFile } = getSuitesByTestFile(this.suite) @@ -478,7 +478,7 @@ addHook({ } }) - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) }) return Runner @@ -504,10 +504,10 @@ addHook({ }, (workerHandlerPackage) => { shimmer.wrap(workerHandlerPackage.prototype, 'exec', exec => function (_, path) { if (!testStartCh.hasSubscribers) { - return exec.apply(this, arguments) + return Reflect.apply(exec, this, arguments) } if (!path?.length) { - return exec.apply(this, arguments) + return Reflect.apply(exec, this, arguments) } const [testSuiteAbsolutePath] = path const testSuiteAsyncResource = new AsyncResource('bound-anonymous-fn') @@ -532,7 +532,7 @@ addHook({ }) try { - const promise = exec.apply(this, arguments) + const promise = Reflect.apply(exec, this, arguments) promise.then( (result) => { const status = result.failureCount === 0 ? 'pass' : 'fail' @@ -572,7 +572,7 @@ addHook({ }, (ParallelBufferedRunner, frameworkVersion) => { shimmer.wrap(ParallelBufferedRunner.prototype, 'run', run => function (cb, { files }) { if (!testStartCh.hasSubscribers) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } this.once('start', getOnStartHandler(true, frameworkVersion)) @@ -592,7 +592,7 @@ addHook({ config.isEarlyFlakeDetectionFaulty = true } } - run.apply(this, arguments) + Reflect.apply(run, this, arguments) }) return this @@ -613,7 +613,7 @@ addHook({ shimmer.wrap(BufferedWorkerPool.prototype, 'run', run => async function (testSuiteAbsolutePath, workerArgs) { if (!testStartCh.hasSubscribers || !config.isKnownTestsEnabled) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } const testPath = getTestSuitePath(testSuiteAbsolutePath, process.cwd()) @@ -621,24 +621,21 @@ addHook({ const testSuiteQuarantinedTests = config.quarantinedTests?.modules?.mocha?.suites?.[testPath] || [] // We pass the known tests for the test file to the worker - const testFileResult = await run.apply( - this, - [ - testSuiteAbsolutePath, - { - ...workerArgs, - _ddEfdNumRetries: config.earlyFlakeDetectionNumRetries, - _ddIsEfdEnabled: config.isEarlyFlakeDetectionEnabled, - _ddIsQuarantinedEnabled: config.isQuarantinedTestsEnabled, - _ddQuarantinedTests: testSuiteQuarantinedTests, - _ddKnownTests: { - mocha: { - [testPath]: testSuiteKnownTests - } + const testFileResult = await Reflect.apply(run, this, [ + testSuiteAbsolutePath, + { + ...workerArgs, + _ddEfdNumRetries: config.earlyFlakeDetectionNumRetries, + _ddIsEfdEnabled: config.isEarlyFlakeDetectionEnabled, + _ddIsQuarantinedEnabled: config.isQuarantinedTestsEnabled, + _ddQuarantinedTests: testSuiteQuarantinedTests, + _ddKnownTests: { + mocha: { + [testPath]: testSuiteKnownTests } } - ] - ) + } + ]) const tests = testFileResult .events .filter(event => event.eventName === 'test end') diff --git a/packages/datadog-instrumentations/src/mocha/utils.js b/packages/datadog-instrumentations/src/mocha/utils.js index 40fcbdc4ff7..35374037395 100644 --- a/packages/datadog-instrumentations/src/mocha/utils.js +++ b/packages/datadog-instrumentations/src/mocha/utils.js @@ -132,7 +132,7 @@ function getTestAsyncResource (test) { function runnableWrapper (RunnablePackage, libraryConfig) { shimmer.wrap(RunnablePackage.prototype, 'run', run => function () { if (!testStartCh.hasSubscribers) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } // Flaky test retries does not work in parallel mode if (libraryConfig?.isFlakyTestRetriesEnabled) { @@ -169,7 +169,7 @@ function runnableWrapper (RunnablePackage, libraryConfig) { } } - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) }) return RunnablePackage } @@ -392,7 +392,7 @@ function getRunTestsWrapper (runTests, config) { }) } - return runTests.apply(this, arguments) + return Reflect.apply(runTests, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/mocha/worker.js b/packages/datadog-instrumentations/src/mocha/worker.js index 88a2b33b498..d82b02eaad1 100644 --- a/packages/datadog-instrumentations/src/mocha/worker.js +++ b/packages/datadog-instrumentations/src/mocha/worker.js @@ -41,7 +41,7 @@ addHook({ delete this.options._ddIsQuarantinedEnabled delete this.options._ddQuarantinedTests } - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) }) return Mocha @@ -57,7 +57,7 @@ addHook({ shimmer.wrap(Runner.prototype, 'run', run => function () { if (!workerFinishCh.hasSubscribers) { - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } // We flush when the worker ends with its test file (a mocha instance in a worker runs a single test file) this.on('end', () => { @@ -74,7 +74,7 @@ addHook({ this.on('pending', getOnPendingHandler()) - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) }) return Runner }) diff --git a/packages/datadog-instrumentations/src/moleculer/client.js b/packages/datadog-instrumentations/src/moleculer/client.js index 58b33241392..00ab3719d40 100644 --- a/packages/datadog-instrumentations/src/moleculer/client.js +++ b/packages/datadog-instrumentations/src/moleculer/client.js @@ -19,7 +19,7 @@ function wrapCall (call) { return callResource.runInAsyncScope(() => { startChannel.publish({ actionName, params, opts }) - const promise = call.apply(this, arguments) + const promise = Reflect.apply(call, this, arguments) const broker = this const ctx = promise.ctx diff --git a/packages/datadog-instrumentations/src/moleculer/server.js b/packages/datadog-instrumentations/src/moleculer/server.js index 425d1cf05f4..2e2d5e84e72 100644 --- a/packages/datadog-instrumentations/src/moleculer/server.js +++ b/packages/datadog-instrumentations/src/moleculer/server.js @@ -13,7 +13,7 @@ function wrapRegisterMiddlewares (registerMiddlewares) { this.middlewares.add(createMiddleware()) } - return registerMiddlewares.apply(this, arguments) + return Reflect.apply(registerMiddlewares, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/mongodb-core.js b/packages/datadog-instrumentations/src/mongodb-core.js index 0441d95d5f0..ca15279f9f5 100644 --- a/packages/datadog-instrumentations/src/mongodb-core.js +++ b/packages/datadog-instrumentations/src/mongodb-core.js @@ -69,7 +69,7 @@ addHook({ name: 'mongodb', versions: ['>=3.5.4 <4.11.0'], file: 'lib/utils.js' } arguments[callbackIndex] = asyncResource.bind(callback) } - return maybePromise.apply(this, arguments) + return Reflect.apply(maybePromise, this, arguments) }) return util }) @@ -88,7 +88,7 @@ function wrapWp (wp) { function wrapUnifiedCommand (command, operation, name) { const wrapped = function (server, ns, ops) { if (!startCh.hasSubscribers) { - return command.apply(this, arguments) + return Reflect.apply(command, this, arguments) } return instrument(operation, command, this, arguments, server, ns, ops, { name }) } @@ -98,7 +98,7 @@ function wrapUnifiedCommand (command, operation, name) { function wrapConnectionCommand (command, operation, name, instrumentFn = instrument) { const wrapped = function (ns, ops) { if (!startCh.hasSubscribers) { - return command.apply(this, arguments) + return Reflect.apply(command, this, arguments) } const hostParts = typeof this.address === 'string' ? this.address.split(':') : '' const options = hostParts.length === 2 @@ -115,7 +115,7 @@ function wrapConnectionCommand (command, operation, name, instrumentFn = instrum function wrapQuery (query, operation, name) { const wrapped = function () { if (!startCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const pool = this.server.s.pool const ns = this.ns @@ -129,7 +129,7 @@ function wrapQuery (query, operation, name) { function wrapCursor (cursor, operation, name) { const wrapped = function () { if (!startCh.hasSubscribers) { - return cursor.apply(this, arguments) + return Reflect.apply(cursor, this, arguments) } const pool = this.server.s.pool const ns = this.ns @@ -141,7 +141,7 @@ function wrapCursor (cursor, operation, name) { function wrapCommand (command, operation, name) { const wrapped = function (ns, ops) { if (!startCh.hasSubscribers) { - return command.apply(this, arguments) + return Reflect.apply(command, this, arguments) } return instrument(operation, command, this, arguments, this, ns, ops, { name }) } @@ -172,7 +172,7 @@ function instrument (operation, command, ctx, args, server, ns, ops, options = { finishCh.publish() if (callback) { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) } })) diff --git a/packages/datadog-instrumentations/src/mongodb.js b/packages/datadog-instrumentations/src/mongodb.js index f73aa21652a..fc918448888 100644 --- a/packages/datadog-instrumentations/src/mongodb.js +++ b/packages/datadog-instrumentations/src/mongodb.js @@ -38,7 +38,7 @@ addHook({ name: 'mongodb', versions: ['>=3.3 <5', '5', '>=6'] }, mongodb => { shimmer.wrap(mongodb.Collection.prototype, methodName, method => { return function () { if (!startCh.hasSubscribers) { - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -54,7 +54,7 @@ addHook({ name: 'mongodb', versions: ['>=3.3 <5', '5', '>=6'] }, mongodb => { methodName }) - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) }) } }) diff --git a/packages/datadog-instrumentations/src/mongoose.js b/packages/datadog-instrumentations/src/mongoose.js index 8116e38380e..81baabc9b15 100644 --- a/packages/datadog-instrumentations/src/mongoose.js +++ b/packages/datadog-instrumentations/src/mongoose.js @@ -13,7 +13,7 @@ function wrapAddQueue (addQueue) { arguments[0] = AsyncResource.bind((...args) => this[name](...args)) } - return addQueue.apply(this, arguments) + return Reflect.apply(addQueue, this, arguments) } } @@ -65,7 +65,7 @@ addHook({ shimmer.wrap(Model, methodName, method => { return function wrappedModelMethod () { if (!startCh.hasSubscribers) { - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -90,7 +90,7 @@ addHook({ return function () { finish() - return originalCb.apply(this, arguments) + return Reflect.apply(originalCb, this, arguments) } }) @@ -106,7 +106,7 @@ addHook({ methodName }) - const res = method.apply(this, arguments) + const res = Reflect.apply(method, this, arguments) // if it is not callback, wrap exec method and its then if (!callbackWrapped) { @@ -116,7 +116,7 @@ addHook({ wrapCallbackIfExist(arguments) } - const execResult = originalExec.apply(this, arguments) + const execResult = Reflect.apply(originalExec, this, arguments) if (callbackWrapped || typeof execResult?.then !== 'function') { return execResult @@ -132,7 +132,7 @@ addHook({ finish() if (resolve) { - return resolve.apply(this, arguments) + return Reflect.apply(resolve, this, arguments) } }) @@ -140,11 +140,11 @@ addHook({ finish() if (reject) { - return reject.apply(this, arguments) + return Reflect.apply(reject, this, arguments) } }) - return originalThen.apply(this, arguments) + return Reflect.apply(originalThen, this, arguments) } }) @@ -169,7 +169,7 @@ addHook({ file: 'lib/helpers/query/sanitizeFilter.js' }, sanitizeFilter => { return shimmer.wrapFunction(sanitizeFilter, sanitizeFilter => function wrappedSanitizeFilter () { - const sanitizedObject = sanitizeFilter.apply(this, arguments) + const sanitizedObject = Reflect.apply(sanitizeFilter, this, arguments) if (sanitizeFilterFinishCh.hasSubscribers) { sanitizeFilterFinishCh.publish({ diff --git a/packages/datadog-instrumentations/src/mquery.js b/packages/datadog-instrumentations/src/mquery.js index c300736f3fe..cb2e622f719 100644 --- a/packages/datadog-instrumentations/src/mquery.js +++ b/packages/datadog-instrumentations/src/mquery.js @@ -50,7 +50,7 @@ addHook({ } } - return method.apply(this, arguments) + return Reflect.apply(method, this, arguments) } }) }) diff --git a/packages/datadog-instrumentations/src/multer.js b/packages/datadog-instrumentations/src/multer.js index 90fae3a8297..786148db9e4 100644 --- a/packages/datadog-instrumentations/src/multer.js +++ b/packages/datadog-instrumentations/src/multer.js @@ -16,7 +16,7 @@ function publishRequestBodyAndNext (req, res, next) { if (abortController.signal.aborted) return } - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) }) } @@ -26,12 +26,12 @@ addHook({ versions: ['^1.4.4-lts.1'] }, makeMiddleware => { return shimmer.wrapFunction(makeMiddleware, makeMiddleware => function () { - const middleware = makeMiddleware.apply(this, arguments) + const middleware = Reflect.apply(makeMiddleware, this, arguments) return shimmer.wrapFunction(middleware, middleware => function wrapMulterMiddleware (req, res, next) { const nextResource = new AsyncResource('bound-anonymous-fn') arguments[2] = nextResource.bind(publishRequestBodyAndNext(req, res, next)) - return middleware.apply(this, arguments) + return Reflect.apply(middleware, this, arguments) }) }) }) diff --git a/packages/datadog-instrumentations/src/mysql.js b/packages/datadog-instrumentations/src/mysql.js index a7b2c4fb8b9..969baec2309 100644 --- a/packages/datadog-instrumentations/src/mysql.js +++ b/packages/datadog-instrumentations/src/mysql.js @@ -14,7 +14,7 @@ addHook({ name: 'mysql', file: 'lib/Connection.js', versions: ['>=2'] }, Connect shimmer.wrap(Connection.prototype, 'query', query => function () { if (!startCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const sql = arguments[0].sql || arguments[0] @@ -33,7 +33,7 @@ addHook({ name: 'mysql', file: 'lib/Connection.js', versions: ['>=2'] }, Connect arguments[0] = payload.sql } try { - const res = query.apply(this, arguments) + const res = Reflect.apply(query, this, arguments) if (res._callback) { const cb = callbackResource.bind(res._callback) @@ -43,7 +43,7 @@ addHook({ name: 'mysql', file: 'lib/Connection.js', versions: ['>=2'] }, Connect } finishCh.publish(result) - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) })) } else { const cb = asyncResource.bind(function () { @@ -71,12 +71,12 @@ addHook({ name: 'mysql', file: 'lib/Pool.js', versions: ['>=2'] }, Pool => { shimmer.wrap(Pool.prototype, 'getConnection', getConnection => function (cb) { arguments[0] = AsyncResource.bind(cb) - return getConnection.apply(this, arguments) + return Reflect.apply(getConnection, this, arguments) }) shimmer.wrap(Pool.prototype, 'query', query => function () { if (!startPoolQueryCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -94,11 +94,11 @@ addHook({ name: 'mysql', file: 'lib/Pool.js', versions: ['>=2'] }, Pool => { if (typeof cb === 'function') { arguments[arguments.length - 1] = shimmer.wrapFunction(cb, cb => function () { finish() - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) }) } - const retval = query.apply(this, arguments) + const retval = Reflect.apply(query, this, arguments) if (retval && retval.then) { retval.then(finish).catch(finish) diff --git a/packages/datadog-instrumentations/src/mysql2.js b/packages/datadog-instrumentations/src/mysql2.js index bf7cd2dbcd6..46eae4c7621 100644 --- a/packages/datadog-instrumentations/src/mysql2.js +++ b/packages/datadog-instrumentations/src/mysql2.js @@ -16,7 +16,7 @@ function wrapConnection (Connection, version) { const shouldEmitEndAfterQueryAbort = satisfies(version, '>=1.3.3') shimmer.wrap(Connection.prototype, 'addCommand', addCommand => function (cmd) { - if (!startCh.hasSubscribers) return addCommand.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(addCommand, this, arguments) const asyncResource = new AsyncResource('bound-anonymous-fn') const name = cmd && cmd.constructor && cmd.constructor.name @@ -28,15 +28,15 @@ function wrapConnection (Connection, version) { ? wrapExecute(cmd, cmd.execute, asyncResource, this.config) : bindExecute(cmd, cmd.execute, asyncResource) - return asyncResource.bind(addCommand, this).apply(this, arguments) + return Reflect.apply(asyncResource.bind(addCommand, this), this, arguments) }) shimmer.wrap(Connection.prototype, 'query', query => function (sql, values, cb) { - if (!startOuterQueryCh.hasSubscribers) return query.apply(this, arguments) + if (!startOuterQueryCh.hasSubscribers) return Reflect.apply(query, this, arguments) if (typeof sql === 'object') sql = sql?.sql - if (!sql) return query.apply(this, arguments) + if (!sql) return Reflect.apply(query, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -47,7 +47,7 @@ function wrapConnection (Connection, version) { let queryCommand try { - queryCommand = query.apply(this, arguments) + queryCommand = Reflect.apply(query, this, arguments) } finally { this.addCommand = addCommand } @@ -69,15 +69,15 @@ function wrapConnection (Connection, version) { return queryCommand } - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) }) shimmer.wrap(Connection.prototype, 'execute', execute => function (sql, values, cb) { - if (!startOuterQueryCh.hasSubscribers) return execute.apply(this, arguments) + if (!startOuterQueryCh.hasSubscribers) return Reflect.apply(execute, this, arguments) if (typeof sql === 'object') sql = sql?.sql - if (!sql) return execute.apply(this, arguments) + if (!sql) return Reflect.apply(execute, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -88,7 +88,7 @@ function wrapConnection (Connection, version) { let result try { - result = execute.apply(this, arguments) + result = Reflect.apply(execute, this, arguments) } finally { this.addCommand = addCommand } @@ -98,7 +98,7 @@ function wrapConnection (Connection, version) { return result } - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) }) return Connection @@ -109,7 +109,7 @@ function wrapConnection (Connection, version) { this.onResult = asyncResource.bind(this.onResult) } - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) }, cmd)) } @@ -135,7 +135,7 @@ function wrapConnection (Connection, version) { errorCh.publish(error) } finishCh.publish(undefined) - onResult.apply(this, arguments) + Reflect.apply(onResult, this, arguments) }, 'bound-anonymous-fn', this)) } else { this.on('error', asyncResource.bind(error => errorCh.publish(error))) @@ -145,7 +145,7 @@ function wrapConnection (Connection, version) { this.execute = execute try { - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) } catch (err) { errorCh.publish(err) } @@ -157,11 +157,11 @@ function wrapPool (Pool, version) { const shouldEmitEndAfterQueryAbort = satisfies(version, '>=1.3.3') shimmer.wrap(Pool.prototype, 'query', query => function (sql, values, cb) { - if (!startOuterQueryCh.hasSubscribers) return query.apply(this, arguments) + if (!startOuterQueryCh.hasSubscribers) return Reflect.apply(query, this, arguments) if (typeof sql === 'object') sql = sql?.sql - if (!sql) return query.apply(this, arguments) + if (!sql) return Reflect.apply(query, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -172,7 +172,7 @@ function wrapPool (Pool, version) { let queryCommand try { - queryCommand = query.apply(this, arguments) + queryCommand = Reflect.apply(query, this, arguments) } finally { this.getConnection = getConnection } @@ -192,15 +192,15 @@ function wrapPool (Pool, version) { return queryCommand } - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) }) shimmer.wrap(Pool.prototype, 'execute', execute => function (sql, values, cb) { - if (!startOuterQueryCh.hasSubscribers) return execute.apply(this, arguments) + if (!startOuterQueryCh.hasSubscribers) return Reflect.apply(execute, this, arguments) if (typeof sql === 'object') sql = sql?.sql - if (!sql) return execute.apply(this, arguments) + if (!sql) return Reflect.apply(execute, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -216,7 +216,7 @@ function wrapPool (Pool, version) { return } - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) }) return Pool @@ -227,13 +227,13 @@ function wrapPoolCluster (PoolCluster) { const wrappedPoolNamespaces = new WeakSet() shimmer.wrap(PoolCluster.prototype, 'of', of => function () { - const poolNamespace = of.apply(this, arguments) + const poolNamespace = Reflect.apply(of, this, arguments) if (startOuterQueryCh.hasSubscribers && !wrappedPoolNamespaces.has(poolNamespace)) { shimmer.wrap(poolNamespace, 'query', query => function (sql, values, cb) { if (typeof sql === 'object') sql = sql?.sql - if (!sql) return query.apply(this, arguments) + if (!sql) return Reflect.apply(query, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -244,7 +244,7 @@ function wrapPoolCluster (PoolCluster) { let queryCommand try { - queryCommand = query.apply(this, arguments) + queryCommand = Reflect.apply(query, this, arguments) } finally { this.getConnection = getConnection } @@ -262,13 +262,13 @@ function wrapPoolCluster (PoolCluster) { return queryCommand } - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) }) shimmer.wrap(poolNamespace, 'execute', execute => function (sql, values, cb) { if (typeof sql === 'object') sql = sql?.sql - if (!sql) return execute.apply(this, arguments) + if (!sql) return Reflect.apply(execute, this, arguments) const abortController = new AbortController() startOuterQueryCh.publish({ sql, abortController }) @@ -285,7 +285,7 @@ function wrapPoolCluster (PoolCluster) { return } - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) }) wrappedPoolNamespaces.add(poolNamespace) diff --git a/packages/datadog-instrumentations/src/net.js b/packages/datadog-instrumentations/src/net.js index b9862a97681..04013e90133 100644 --- a/packages/datadog-instrumentations/src/net.js +++ b/packages/datadog-instrumentations/src/net.js @@ -30,14 +30,14 @@ addHook({ name: names }, (net, version, name) => { shimmer.wrap(net.Socket.prototype, 'connect', connect => function () { if (!startICPCh.hasSubscribers || !startTCPCh.hasSubscribers) { - return connect.apply(this, arguments) + return Reflect.apply(connect, this, arguments) } const options = getOptions(arguments) const lastIndex = arguments.length - 1 const callback = arguments[lastIndex] - if (!options) return connect.apply(this, arguments) + if (!options) return Reflect.apply(connect, this, arguments) const callbackResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -63,15 +63,15 @@ addHook({ name: names }, (net, version, name) => { case 'ready': case 'connect': return callbackResource.runInAsyncScope(() => { - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) }) default: - return emit.apply(this, arguments) + return Reflect.apply(emit, this, arguments) } }) try { - return connect.apply(this, arguments) + return Reflect.apply(connect, this, arguments) } catch (err) { protocol === 'ipc' ? errorICPCh.publish(err) : errorTCPCh.publish(err) diff --git a/packages/datadog-instrumentations/src/next.js b/packages/datadog-instrumentations/src/next.js index 770d340d567..8ede23196b9 100644 --- a/packages/datadog-instrumentations/src/next.js +++ b/packages/datadog-instrumentations/src/next.js @@ -23,14 +23,14 @@ const encounteredMiddleware = new WeakSet() function wrapHandleRequest (handleRequest) { return function (req, res, pathname, query) { - return instrument(req, res, () => handleRequest.apply(this, arguments)) + return instrument(req, res, () => Reflect.apply(handleRequest, this, arguments)) } } function wrapHandleApiRequest (handleApiRequest) { return function (req, res, pathname, query) { return instrument(req, res, () => { - const promise = handleApiRequest.apply(this, arguments) + const promise = Reflect.apply(handleApiRequest, this, arguments) return promise.then(handled => { if (!handled) return handled @@ -57,38 +57,38 @@ function wrapHandleApiRequestWithMatch (handleApiRequest) { pageLoadChannel.publish({ page }) - return handleApiRequest.apply(this, arguments) + return Reflect.apply(handleApiRequest, this, arguments) }) } } function wrapRenderToHTML (renderToHTML) { return function (req, res, pathname, query, parsedUrl) { - return instrument(req, res, () => renderToHTML.apply(this, arguments)) + return instrument(req, res, () => Reflect.apply(renderToHTML, this, arguments)) } } function wrapRenderErrorToHTML (renderErrorToHTML) { return function (err, req, res, pathname, query) { - return instrument(req, res, err, () => renderErrorToHTML.apply(this, arguments)) + return instrument(req, res, err, () => Reflect.apply(renderErrorToHTML, this, arguments)) } } function wrapRenderToResponse (renderToResponse) { return function (ctx) { - return instrument(ctx.req, ctx.res, () => renderToResponse.apply(this, arguments)) + return instrument(ctx.req, ctx.res, () => Reflect.apply(renderToResponse, this, arguments)) } } function wrapRenderErrorToResponse (renderErrorToResponse) { return function (ctx, err) { - return instrument(ctx.req, ctx.res, err, () => renderErrorToResponse.apply(this, arguments)) + return instrument(ctx.req, ctx.res, err, () => Reflect.apply(renderErrorToResponse, this, arguments)) } } function wrapFindPageComponents (findPageComponents) { return function (pathname, query) { - const result = findPageComponents.apply(this, arguments) + const result = Reflect.apply(findPageComponents, this, arguments) if (result) { pageLoadChannel.publish(getPagePath(pathname)) @@ -169,7 +169,7 @@ function wrapServeStatic (serveStatic) { pageLoadChannel.publish({ page: path, isStatic: true }) } - return serveStatic.apply(this, arguments) + return Reflect.apply(serveStatic, this, arguments) }) } } @@ -204,7 +204,7 @@ addHook({ }, NextRequestAdapter => { shimmer.wrap(NextRequestAdapter.NextRequestAdapter, 'fromNodeNextRequest', fromNodeNextRequest => { return function (nodeNextRequest) { - const nextRequest = fromNodeNextRequest.apply(this, arguments) + const nextRequest = Reflect.apply(fromNodeNextRequest, this, arguments) nodeNextRequestsToNextRequests.set(nodeNextRequest.originalRequest, nextRequest) return nextRequest } @@ -285,7 +285,7 @@ addHook({ const nextUrlDescriptor = Object.getOwnPropertyDescriptor(request.NextRequest.prototype, 'nextUrl') shimmer.wrap(nextUrlDescriptor, 'get', function (originalGet) { return function wrappedGet () { - const nextUrl = originalGet.apply(this, arguments) + const nextUrl = Reflect.apply(originalGet, this, arguments) if (queryParsedChannel.hasSubscribers) { const query = {} for (const key of nextUrl.searchParams.keys()) { @@ -304,7 +304,7 @@ addHook({ shimmer.massWrap(request.NextRequest.prototype, ['text', 'json'], function (originalMethod) { return async function wrappedJson () { - const body = await originalMethod.apply(this, arguments) + const body = await Reflect.apply(originalMethod, this, arguments) bodyParsedChannel.publish({ body }) @@ -314,7 +314,7 @@ addHook({ shimmer.wrap(request.NextRequest.prototype, 'formData', function (originalFormData) { return async function wrappedFormData () { - const body = await originalFormData.apply(this, arguments) + const body = await Reflect.apply(originalFormData, this, arguments) let normalizedBody = body if (typeof body.entries === 'function') { diff --git a/packages/datadog-instrumentations/src/node-serialize.js b/packages/datadog-instrumentations/src/node-serialize.js index 21484bfc605..a13f4866dd9 100644 --- a/packages/datadog-instrumentations/src/node-serialize.js +++ b/packages/datadog-instrumentations/src/node-serialize.js @@ -11,7 +11,7 @@ function wrapUnserialize (serialize) { nodeUnserializeCh.publish({ obj }) } - return serialize.apply(this, arguments) + return Reflect.apply(serialize, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/nyc.js b/packages/datadog-instrumentations/src/nyc.js index 34210a78f06..248778aeac7 100644 --- a/packages/datadog-instrumentations/src/nyc.js +++ b/packages/datadog-instrumentations/src/nyc.js @@ -17,7 +17,7 @@ addHook({ // ignore errors } - return wrap.apply(this, arguments) + return Reflect.apply(wrap, this, arguments) }) return nycPackage }) diff --git a/packages/datadog-instrumentations/src/openai.js b/packages/datadog-instrumentations/src/openai.js index e41db136854..45a9c814929 100644 --- a/packages/datadog-instrumentations/src/openai.js +++ b/packages/datadog-instrumentations/src/openai.js @@ -115,7 +115,7 @@ addHook({ name: 'openai', file: 'dist/api.js', versions: ['>=3.0.0 <4'] }, expor for (const methodName of methodNames) { shimmer.wrap(exports.OpenAIApi.prototype, methodName, fn => function () { if (!ch.start.hasSubscribers) { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) } const ctx = { @@ -209,9 +209,9 @@ function wrapStreamIterator (response, options, n, ctx) { let chunks = [] return function (itr) { return function () { - const iterator = itr.apply(this, arguments) + const iterator = Reflect.apply(itr, this, arguments) shimmer.wrap(iterator, 'next', next => function () { - return next.apply(this, arguments) + return Reflect.apply(next, this, arguments) .then(res => { const { done, value: chunk } = res @@ -275,7 +275,7 @@ for (const shim of V4_PACKAGE_SHIMS) { for (const methodName of methods) { shimmer.wrap(targetPrototype, methodName, methodFn => function () { if (!ch.start.hasSubscribers) { - return methodFn.apply(this, arguments) + return Reflect.apply(methodFn, this, arguments) } // The OpenAI library lets you set `stream: true` on the options arg to any method @@ -304,12 +304,12 @@ for (const shim of V4_PACKAGE_SHIMS) { } return ch.start.runStores(ctx, () => { - const apiProm = methodFn.apply(this, arguments) + const apiProm = Reflect.apply(methodFn, this, arguments) // wrapping `parse` avoids problematic wrapping of `then` when trying to call // `withResponse` in userland code after. This way, we can return the whole `APIPromise` shimmer.wrap(apiProm, 'parse', origApiPromParse => function () { - return origApiPromParse.apply(this, arguments) + return Reflect.apply(origApiPromParse, this, arguments) // the original response is wrapped in a promise, so we need to unwrap it .then(body => Promise.all([this.responsePromise, body])) .then(([{ response, options }, body]) => { diff --git a/packages/datadog-instrumentations/src/oracledb.js b/packages/datadog-instrumentations/src/oracledb.js index 61db967fdfe..16951a914ad 100644 --- a/packages/datadog-instrumentations/src/oracledb.js +++ b/packages/datadog-instrumentations/src/oracledb.js @@ -25,7 +25,7 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { shimmer.wrap(oracledb.Connection.prototype, 'execute', execute => { return function wrappedExecute (dbQuery, ...args) { if (!startChannel.hasSubscribers) { - return execute.apply(this, arguments) + return Reflect.apply(execute, this, arguments) } if (arguments.length && typeof arguments[arguments.length - 1] === 'function') { @@ -33,7 +33,7 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { const outerAr = new AsyncResource('apm:oracledb:outer-scope') arguments[arguments.length - 1] = shimmer.wrapFunction(cb, cb => function wrappedCb (err, result) { finish(err) - return outerAr.runInAsyncScope(() => cb.apply(this, arguments)) + return outerAr.runInAsyncScope(() => Reflect.apply(cb, this, arguments)) }) } @@ -41,7 +41,7 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { const connAttrs = connectionAttributes.get(this) startChannel.publish({ query: dbQuery, connAttrs }) try { - let result = execute.apply(this, arguments) + let result = Reflect.apply(execute, this, arguments) if (result && typeof result.then === 'function') { result = result.then( @@ -74,9 +74,9 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { callback(err, connection) }) - getConnection.apply(this, arguments) + Reflect.apply(getConnection, this, arguments) } else { - return getConnection.apply(this, arguments).then((connection) => { + return Reflect.apply(getConnection, this, arguments).then((connection) => { connectionAttributes.set(connection, connAttrs) return connection }) @@ -93,9 +93,9 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { callback(err, pool) }) - createPool.apply(this, arguments) + Reflect.apply(createPool, this, arguments) } else { - return createPool.apply(this, arguments).then((pool) => { + return Reflect.apply(createPool, this, arguments).then((pool) => { poolAttributes.set(pool, poolAttrs) return pool }) @@ -115,9 +115,9 @@ addHook({ name: 'oracledb', versions: ['>=5'] }, oracledb => { } callback(err, connection) }) - getConnection.apply(this, arguments) + Reflect.apply(getConnection, this, arguments) } else { - return getConnection.apply(this, arguments).then((connection) => { + return Reflect.apply(getConnection, this, arguments).then((connection) => { connectionAttributes.set(connection, poolAttributes.get(this)) return connection }) diff --git a/packages/datadog-instrumentations/src/paperplane.js b/packages/datadog-instrumentations/src/paperplane.js index 27c9162d638..ef01105fbcf 100644 --- a/packages/datadog-instrumentations/src/paperplane.js +++ b/packages/datadog-instrumentations/src/paperplane.js @@ -35,7 +35,7 @@ const wrapMount = mount => opts => { return function (req, res) { handleChannel.publish(req) - return handler.apply(this, arguments) + return Reflect.apply(handler, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/passport-utils.js b/packages/datadog-instrumentations/src/passport-utils.js index de1cd090a71..5ca21305480 100644 --- a/packages/datadog-instrumentations/src/passport-utils.js +++ b/packages/datadog-instrumentations/src/passport-utils.js @@ -17,7 +17,7 @@ function wrapVerifiedAndPublish (framework, username, verified) { if (abortController.signal.aborted) return } - return verified.apply(this, arguments) + return Reflect.apply(verified, this, arguments) } }) } @@ -35,7 +35,7 @@ function wrapVerify (verify) { } } - return verify.apply(this, arguments) + return Reflect.apply(verify, this, arguments) } } @@ -48,7 +48,7 @@ function wrapStrategy (Strategy) { arguments[1] = wrapVerify(arguments[1]) } - return Strategy.apply(this, arguments) + return Reflect.apply(Strategy, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/passport.js b/packages/datadog-instrumentations/src/passport.js index 58c8b870cb9..d03933d4598 100644 --- a/packages/datadog-instrumentations/src/passport.js +++ b/packages/datadog-instrumentations/src/passport.js @@ -15,13 +15,13 @@ function wrapDone (done) { if (abortController.signal.aborted) return } - return done.apply(this, arguments) + return Reflect.apply(done, this, arguments) } } function wrapDeserializeUser (deserializeUser) { return function wrappedDeserializeUser (fn, req, done) { - if (typeof fn === 'function') return deserializeUser.apply(this, arguments) + if (typeof fn === 'function') return Reflect.apply(deserializeUser, this, arguments) if (typeof req === 'function') { done = req @@ -30,7 +30,7 @@ function wrapDeserializeUser (deserializeUser) { arguments[2] = wrapDone(done) } - return deserializeUser.apply(this, arguments) + return Reflect.apply(deserializeUser, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/pg.js b/packages/datadog-instrumentations/src/pg.js index 331557cd239..4b378abf90f 100644 --- a/packages/datadog-instrumentations/src/pg.js +++ b/packages/datadog-instrumentations/src/pg.js @@ -28,7 +28,7 @@ addHook({ name: 'pg', file: 'lib/native/index.js', versions: ['>=8.0.3'] }, Clie function wrapQuery (query) { return function () { if (!startCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') @@ -106,7 +106,7 @@ function wrapQuery (query) { arguments[0] = pgQuery - const retval = query.apply(this, arguments) + const retval = Reflect.apply(query, this, arguments) const queryQueue = this.queryQueue || this._queryQueue const activeQuery = this.activeQuery || this._activeQuery @@ -120,7 +120,7 @@ function wrapQuery (query) { const originalCallback = callbackResource.bind(newQuery.callback) newQuery.callback = function (err, res) { finish(err, res) - return originalCallback.apply(this, arguments) + return Reflect.apply(originalCallback, this, arguments) } } else if (newQuery.once) { newQuery @@ -142,7 +142,7 @@ function wrapQuery (query) { function wrapPoolQuery (query) { return function () { if (!startPoolQueryCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -179,11 +179,11 @@ function wrapPoolQuery (query) { if (typeof cb === 'function') { arguments[arguments.length - 1] = shimmer.wrapFunction(cb, cb => function () { finish() - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) }) } - const retval = query.apply(this, arguments) + const retval = Reflect.apply(query, this, arguments) if (retval && retval.then) { retval.then(() => { diff --git a/packages/datadog-instrumentations/src/pino.js b/packages/datadog-instrumentations/src/pino.js index 503986519ae..a9289e10f65 100644 --- a/packages/datadog-instrumentations/src/pino.js +++ b/packages/datadog-instrumentations/src/pino.js @@ -8,7 +8,7 @@ const shimmer = require('../../datadog-shimmer') function wrapPino (symbol, wrapper, pino) { return function pinoWithTrace () { - const instance = pino.apply(this, arguments) + const instance = Reflect.apply(pino, this, arguments) Object.defineProperty(instance, symbol, { configurable: true, @@ -30,7 +30,7 @@ function wrapAsJson (asJson) { ch.publish(payload) arguments[0] = payload.message - return asJson.apply(this, arguments) + return Reflect.apply(asJson, this, arguments) } } @@ -40,7 +40,7 @@ function wrapMixin (mixin) { let obj = {} if (mixin) { - obj = mixin.apply(this, arguments) + obj = Reflect.apply(mixin, this, arguments) } const payload = { message: obj } @@ -56,19 +56,19 @@ function wrapPrettifyObject (prettifyObject) { const payload = { message: input.input } ch.publish(payload) input.input = payload.message - return prettifyObject.apply(this, arguments) + return Reflect.apply(prettifyObject, this, arguments) } } function wrapPrettyFactory (prettyFactory) { const ch = channel('apm:pino:log') return function prettyFactoryWithTrace () { - const pretty = prettyFactory.apply(this, arguments) + const pretty = Reflect.apply(prettyFactory, this, arguments) return function prettyWithTrace (obj) { const payload = { message: obj } ch.publish(payload) arguments[0] = payload.message - return pretty.apply(this, arguments) + return Reflect.apply(pretty, this, arguments) } } } diff --git a/packages/datadog-instrumentations/src/playwright.js b/packages/datadog-instrumentations/src/playwright.js index ee219e5290c..2952287c5de 100644 --- a/packages/datadog-instrumentations/src/playwright.js +++ b/packages/datadog-instrumentations/src/playwright.js @@ -355,7 +355,7 @@ function testEndHandler (test, annotations, testStatus, error, isTimeout) { function dispatcherRunWrapper (run) { return function () { remainingTestsByFile = getTestsBySuiteFromTestsById(this._testById) - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } } @@ -367,7 +367,7 @@ function dispatcherRunWrapperNew (run) { this._ddAllTests = testGroups.map(g => g.tests).flat() } remainingTestsByFile = getTestsBySuiteFromTestGroups(arguments[0]) - return run.apply(this, arguments) + return Reflect.apply(run, this, arguments) } } @@ -375,7 +375,7 @@ function dispatcherHook (dispatcherExport) { shimmer.wrap(dispatcherExport.Dispatcher.prototype, 'run', dispatcherRunWrapper) shimmer.wrap(dispatcherExport.Dispatcher.prototype, '_createWorker', createWorker => function () { const dispatcher = this - const worker = createWorker.apply(this, arguments) + const worker = Reflect.apply(createWorker, this, arguments) worker.process.on('message', ({ method, params }) => { if (method === 'testBegin') { const { test } = dispatcher._testById.get(params.testId) @@ -402,7 +402,7 @@ function dispatcherHookNew (dispatcherExport, runWrapper) { shimmer.wrap(dispatcherExport.Dispatcher.prototype, 'run', runWrapper) shimmer.wrap(dispatcherExport.Dispatcher.prototype, '_createWorker', createWorker => function () { const dispatcher = this - const worker = createWorker.apply(this, arguments) + const worker = Reflect.apply(createWorker, this, arguments) worker.on('testBegin', ({ testId }) => { const test = getTestByTestId(dispatcher, testId) @@ -491,7 +491,7 @@ function runnerHook (runnerExport, playwrightVersion) { }) } - const runAllTestsReturn = await runAllTests.apply(this, arguments) + const runAllTestsReturn = await Reflect.apply(runAllTests, this, arguments) Object.values(remainingTestsByFile).forEach(tests => { // `tests` should normally be empty, but if it isn't, @@ -595,9 +595,9 @@ addHook({ async function newCreateRootSuite () { if (!isKnownTestsEnabled && !isQuarantinedTestsEnabled) { - return oldCreateRootSuite.apply(this, arguments) + return Reflect.apply(oldCreateRootSuite, this, arguments) } - const rootSuite = await oldCreateRootSuite.apply(this, arguments) + const rootSuite = await Reflect.apply(oldCreateRootSuite, this, arguments) const allTests = rootSuite.allTests() diff --git a/packages/datadog-instrumentations/src/process.js b/packages/datadog-instrumentations/src/process.js index 429b0d8f574..dbd463763c8 100644 --- a/packages/datadog-instrumentations/src/process.js +++ b/packages/datadog-instrumentations/src/process.js @@ -19,7 +19,7 @@ if (process.setUncaughtExceptionCaptureCallback) { } } - const result = originalSetUncaughtExceptionCaptureCallback.apply(this, arguments) + const result = Reflect.apply(originalSetUncaughtExceptionCaptureCallback, this, arguments) currentCallback = newCallback diff --git a/packages/datadog-instrumentations/src/protobufjs.js b/packages/datadog-instrumentations/src/protobufjs.js index 79cbb4ee3a1..54563c6939e 100644 --- a/packages/datadog-instrumentations/src/protobufjs.js +++ b/packages/datadog-instrumentations/src/protobufjs.js @@ -9,10 +9,10 @@ function wrapSerialization (messageClass) { if (messageClass?.encode) { shimmer.wrap(messageClass, 'encode', original => function () { if (!serializeChannel.hasSubscribers) { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } serializeChannel.publish({ messageClass: this }) - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) }) } } @@ -21,9 +21,9 @@ function wrapDeserialization (messageClass) { if (messageClass?.decode) { shimmer.wrap(messageClass, 'decode', original => function () { if (!deserializeChannel.hasSubscribers) { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) deserializeChannel.publish({ messageClass: result }) return result }) @@ -33,7 +33,7 @@ function wrapDeserialization (messageClass) { function wrapSetup (messageClass) { if (messageClass?.setup) { shimmer.wrap(messageClass, 'setup', original => function () { - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) wrapSerialization(messageClass) wrapDeserialization(messageClass) @@ -73,7 +73,7 @@ function wrapReflection (protobuf) { reflectionMethods.forEach(method => { shimmer.wrap(method.target, method.name, original => function () { - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) if (result.nested) { for (const type in result.nested) { wrapSetup(result.nested[type]) @@ -96,7 +96,7 @@ addHook({ versions: ['>=6.8.0'] }, protobuf => { shimmer.wrap(protobuf.Root.prototype, 'load', original => function () { - const result = original.apply(this, arguments) + const result = Reflect.apply(original, this, arguments) if (isPromise(result)) { return result.then(root => { wrapProtobufClasses(root) @@ -110,7 +110,7 @@ addHook({ }) shimmer.wrap(protobuf.Root.prototype, 'loadSync', original => function () { - const root = original.apply(this, arguments) + const root = Reflect.apply(original, this, arguments) wrapProtobufClasses(root) return root }) diff --git a/packages/datadog-instrumentations/src/pug.js b/packages/datadog-instrumentations/src/pug.js index 4322ed265cb..a933f672d9c 100644 --- a/packages/datadog-instrumentations/src/pug.js +++ b/packages/datadog-instrumentations/src/pug.js @@ -11,7 +11,7 @@ function wrapCompile (compile) { pugCompileCh.publish({ source }) } - return compile.apply(this, arguments) + return Reflect.apply(compile, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/redis.js b/packages/datadog-instrumentations/src/redis.js index 8da93ae08ab..1e5e69d691c 100644 --- a/packages/datadog-instrumentations/src/redis.js +++ b/packages/datadog-instrumentations/src/redis.js @@ -16,7 +16,7 @@ let createClientUrl function wrapAddCommand (addCommand) { return function (command) { if (!startCh.hasSubscribers) { - return addCommand.apply(this, arguments) + return Reflect.apply(addCommand, this, arguments) } const name = command[0] @@ -26,7 +26,7 @@ function wrapAddCommand (addCommand) { return asyncResource.runInAsyncScope(() => { start(this, name, args, this._url) - const res = addCommand.apply(this, arguments) + const res = Reflect.apply(addCommand, this, arguments) const onResolve = asyncResource.bind(() => finish(finishCh, errorCh)) const onReject = asyncResource.bind(err => finish(finishCh, errorCh, err)) @@ -60,7 +60,7 @@ function wrapCommandQueueClass (cls) { function wrapCreateClient (request) { return function (opts) { createClientUrl = opts && opts.url - const ret = request.apply(this, arguments) + const ret = Reflect.apply(request, this, arguments) createClientUrl = undefined return ret } @@ -90,9 +90,9 @@ addHook({ name: '@redis/client', file: 'dist/lib/client/commands-queue.js', vers addHook({ name: 'redis', versions: ['>=2.6 <4'] }, redis => { shimmer.wrap(redis.RedisClient.prototype, 'internal_send_command', internalSendCommand => function (options) { - if (!startCh.hasSubscribers) return internalSendCommand.apply(this, arguments) + if (!startCh.hasSubscribers) return Reflect.apply(internalSendCommand, this, arguments) - if (!options.callback) return internalSendCommand.apply(this, arguments) + if (!options.callback) return Reflect.apply(internalSendCommand, this, arguments) const callbackResource = new AsyncResource('bound-anonymous-fn') const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -104,7 +104,7 @@ addHook({ name: 'redis', versions: ['>=2.6 <4'] }, redis => { options.callback = asyncResource.bind(wrapCallback(finishCh, errorCh, cb)) try { - return internalSendCommand.apply(this, arguments) + return Reflect.apply(internalSendCommand, this, arguments) } catch (err) { errorCh.publish(err) @@ -118,7 +118,7 @@ addHook({ name: 'redis', versions: ['>=2.6 <4'] }, redis => { addHook({ name: 'redis', versions: ['>=0.12 <2.6'] }, redis => { shimmer.wrap(redis.RedisClient.prototype, 'send_command', sendCommand => function (command, args, callback) { if (!startCh.hasSubscribers) { - return sendCommand.apply(this, arguments) + return Reflect.apply(sendCommand, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') @@ -138,7 +138,7 @@ addHook({ name: 'redis', versions: ['>=0.12 <2.6'] }, redis => { } try { - return sendCommand.apply(this, arguments) + return Reflect.apply(sendCommand, this, arguments) } catch (err) { errorCh.publish(err) @@ -159,7 +159,7 @@ function wrapCallback (finishCh, errorCh, callback) { return shimmer.wrapFunction(callback, callback => function (err) { finish(finishCh, errorCh, err) if (callback) { - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) } }) } diff --git a/packages/datadog-instrumentations/src/restify.js b/packages/datadog-instrumentations/src/restify.js index b21689fa734..d3d448ff112 100644 --- a/packages/datadog-instrumentations/src/restify.js +++ b/packages/datadog-instrumentations/src/restify.js @@ -15,7 +15,7 @@ const nextChannel = channel('apm:restify:middleware:next') function wrapSetupRequest (setupRequest) { return function (req, res) { handleChannel.publish({ req, res }) - return setupRequest.apply(this, arguments) + return Reflect.apply(setupRequest, this, arguments) } } @@ -50,7 +50,7 @@ function wrapFn (fn) { enterChannel.publish({ req, route }) try { - const result = fn.apply(this, arguments) + const result = Reflect.apply(fn, this, arguments) if (result !== null && typeof result === 'object' && typeof result.then === 'function') { return result.then(function () { nextChannel.publish({ req }) @@ -80,7 +80,7 @@ function wrapNext (req, next) { nextChannel.publish({ req }) finishChannel.publish({ req }) - next.apply(this, arguments) + Reflect.apply(next, this, arguments) }) } diff --git a/packages/datadog-instrumentations/src/rhea.js b/packages/datadog-instrumentations/src/rhea.js index 205e8730460..9ff1996795f 100644 --- a/packages/datadog-instrumentations/src/rhea.js +++ b/packages/datadog-instrumentations/src/rhea.js @@ -27,7 +27,7 @@ const contexts = new WeakMap() // key: delivery Fn, val: context addHook({ name: 'rhea', versions: ['>=1'] }, rhea => { shimmer.wrap(rhea.message, 'encode', encode => function (msg) { encodeSendCh.publish(msg) - return encode.apply(this, arguments) + return Reflect.apply(encode, this, arguments) }) return rhea @@ -39,7 +39,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/link.js' }, obj => { shimmer.wrap(Sender.prototype, 'send', send => function (msg, tag, format) { if (!canTrace(this)) { // we can't handle disconnects or ending spans, so we can't safely instrument - return send.apply(this, arguments) + return Reflect.apply(send, this, arguments) } const { host, port } = getHostAndPort(this.connection) @@ -52,7 +52,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/link.js' }, obj => { const asyncResource = new AsyncResource('bound-anonymous-fn') return asyncResource.runInAsyncScope(() => { startSendCh.publish({ targetAddress, host, port, msg }) - const delivery = send.apply(this, arguments) + const delivery = Reflect.apply(send, this, arguments) const context = { asyncResource, connection: this.connection @@ -73,7 +73,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/link.js' }, obj => { shimmer.wrap(Receiver.prototype, 'dispatch', dispatch => function (eventName, msgObj) { if (!canTrace(this)) { // we can't handle disconnects or ending spans, so we can't safely instrument - return dispatch.apply(this, arguments) + return Reflect.apply(dispatch, this, arguments) } if (eventName === 'message' && msgObj) { @@ -91,7 +91,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/link.js' }, obj => { addToInFlightDeliveries(this.connection, msgObj.delivery) } try { - return dispatch.apply(this, arguments) + return Reflect.apply(dispatch, this, arguments) } catch (err) { errorReceiveCh.publish(err) @@ -100,7 +100,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/link.js' }, obj => { }) } - return dispatch.apply(this, arguments) + return Reflect.apply(dispatch, this, arguments) }) return obj }) @@ -124,7 +124,7 @@ addHook({ name: 'rhea', versions: ['>=1'], file: 'lib/connection.js' }, Connecti }) } } - return dispatch.apply(this, arguments) + return Reflect.apply(dispatch, this, arguments) }) return Connection }) @@ -156,11 +156,11 @@ function wrapDeliveryUpdate (obj, update) { return shimmer.wrapFunction(cb, cb => AsyncResource.bind(function wrappedUpdate (settled, stateData) { const state = getStateFromData(stateData) dispatchReceiveCh.publish({ state }) - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) })) } return function wrappedUpdate (settled, stateData) { - return update.apply(this, arguments) + return Reflect.apply(update, this, arguments) } } @@ -199,7 +199,7 @@ function patchCircularBuffer (proto, Session) { return shouldPop })) - return popIf.apply(this, arguments) + return Reflect.apply(popIf, this, arguments) }) patched.add(CircularBuffer.prototype) const Session = proto.constructor diff --git a/packages/datadog-instrumentations/src/router.js b/packages/datadog-instrumentations/src/router.js index bc9ff6152e5..c5a87b24347 100644 --- a/packages/datadog-instrumentations/src/router.js +++ b/packages/datadog-instrumentations/src/router.js @@ -19,7 +19,7 @@ function createWrapRouterMethod (name) { original._name = original._name || layer.name const handle = shimmer.wrapFunction(original, original => function () { - if (!enterChannel.hasSubscribers) return original.apply(this, arguments) + if (!enterChannel.hasSubscribers) return Reflect.apply(original, this, arguments) const matchers = layerMatchers.get(layer) const lastIndex = arguments.length - 1 @@ -47,7 +47,7 @@ function createWrapRouterMethod (name) { enterChannel.publish({ name, req, route }) try { - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } catch (error) { errorChannel.publish({ req, error }) nextChannel.publish({ req }) @@ -97,7 +97,7 @@ function createWrapRouterMethod (name) { nextChannel.publish({ req }) finishChannel.publish({ req }) - next.apply(this, arguments) + Reflect.apply(next, this, arguments) }) } @@ -152,7 +152,7 @@ function createWrapRouterMethod (name) { function wrapMethod (original) { return shimmer.wrapFunction(original, original => function methodWithTrace (fn) { const offset = this.stack ? [].concat(this.stack).length : 0 - const router = original.apply(this, arguments) + const router = Reflect.apply(original, this, arguments) if (typeof this.stack === 'function') { this.stack = [{ handle: this.stack }] @@ -181,7 +181,7 @@ const queryParserReadCh = channel('datadog:query:read:finish') addHook({ name: 'router', versions: ['>=2'] }, Router => { const WrappedRouter = shimmer.wrapFunction(Router, function (originalRouter) { return function wrappedMethod () { - const router = originalRouter.apply(this, arguments) + const router = Reflect.apply(originalRouter, this, arguments) shimmer.wrap(router, 'handle', function wrapHandle (originalHandle) { return function wrappedHandle (req, res, next) { @@ -193,7 +193,7 @@ addHook({ name: 'router', versions: ['>=2'] }, Router => { if (abortController.signal.aborted) return } - return originalHandle.apply(this, arguments) + return Reflect.apply(originalHandle, this, arguments) } }) @@ -227,7 +227,7 @@ function wrapHandleRequest (original) { if (abortController.signal.aborted) return } - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } } @@ -257,11 +257,11 @@ function wrapParam (original) { if (abortController.signal.aborted) return } - return originalFn.apply(this, arguments) + return Reflect.apply(originalFn, this, arguments) } }) - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/selenium.js b/packages/datadog-instrumentations/src/selenium.js index 141aa967e40..af734bb8a8d 100644 --- a/packages/datadog-instrumentations/src/selenium.js +++ b/packages/datadog-instrumentations/src/selenium.js @@ -24,13 +24,13 @@ addHook({ // TODO: do not turn this into async. Use promises shimmer.wrap(seleniumPackage.WebDriver.prototype, 'get', get => async function () { if (!ciSeleniumDriverGetStartCh.hasSubscribers) { - return get.apply(this, arguments) + return Reflect.apply(get, this, arguments) } let traceId const setTraceId = (inputTraceId) => { traceId = inputTraceId } - const getResult = await get.apply(this, arguments) + const getResult = await Reflect.apply(get, this, arguments) const isRumActive = await this.executeScript(IS_RUM_ACTIVE_SCRIPT) const capabilities = await this.getCapabilities() @@ -55,7 +55,7 @@ addHook({ shimmer.wrap(seleniumPackage.WebDriver.prototype, 'quit', quit => async function () { if (!ciSeleniumDriverGetStartCh.hasSubscribers) { - return quit.apply(this, arguments) + return Reflect.apply(quit, this, arguments) } const isRumActive = await this.executeScript(RUM_STOP_SESSION_SCRIPT) @@ -69,7 +69,7 @@ addHook({ await this.manage().deleteCookie(DD_CIVISIBILITY_TEST_EXECUTION_ID_COOKIE_NAME) } - return quit.apply(this, arguments) + return Reflect.apply(quit, this, arguments) }) return seleniumPackage diff --git a/packages/datadog-instrumentations/src/sequelize.js b/packages/datadog-instrumentations/src/sequelize.js index d8e41b17704..5079ff8fe22 100644 --- a/packages/datadog-instrumentations/src/sequelize.js +++ b/packages/datadog-instrumentations/src/sequelize.js @@ -15,7 +15,7 @@ addHook({ name: 'sequelize', versions: ['>=4'] }, Sequelize => { shimmer.wrap(Sequelize.prototype, 'query', query => { return function (sql, options) { if (!startCh.hasSubscribers) { - return query.apply(this, arguments) + return Reflect.apply(query, this, arguments) } const asyncResource = new AsyncResource('bound-anonymous-fn') @@ -38,17 +38,17 @@ addHook({ name: 'sequelize', versions: ['>=4'] }, Sequelize => { }, this).apply(this) } - return asyncResource.bind(function () { + return Reflect.apply(asyncResource.bind(function () { startCh.publish({ sql, dialect }) - const promise = query.apply(this, arguments) + const promise = Reflect.apply(query, this, arguments) promise.then(onFinish, () => { onFinish() }) return promise - }, this).apply(this, arguments) + }, this), this, arguments) } }) diff --git a/packages/datadog-instrumentations/src/sharedb.js b/packages/datadog-instrumentations/src/sharedb.js index f0851874de4..62981cd965d 100644 --- a/packages/datadog-instrumentations/src/sharedb.js +++ b/packages/datadog-instrumentations/src/sharedb.js @@ -54,11 +54,11 @@ addHook({ name: 'sharedb', versions: ['>=1'], file: 'lib/agent.js' }, Agent => { } finishCh.publish({ request, res }) - return callback.apply(this, arguments) + return Reflect.apply(callback, this, arguments) })) try { - return origHandleMessageFn.apply(this, arguments) + return Reflect.apply(origHandleMessageFn, this, arguments) } catch (error) { errorCh.publish(error) diff --git a/packages/datadog-instrumentations/src/tedious.js b/packages/datadog-instrumentations/src/tedious.js index 3a80b03ad75..24d9e044608 100644 --- a/packages/datadog-instrumentations/src/tedious.js +++ b/packages/datadog-instrumentations/src/tedious.js @@ -13,13 +13,13 @@ addHook({ name: 'tedious', versions: ['>=1.0.0'] }, tedious => { const errorCh = channel('apm:tedious:request:error') shimmer.wrap(tedious.Connection.prototype, 'makeRequest', makeRequest => function (request) { if (!startCh.hasSubscribers) { - return makeRequest.apply(this, arguments) + return Reflect.apply(makeRequest, this, arguments) } const queryOrProcedure = getQueryOrProcedure(request) if (!queryOrProcedure) { - return makeRequest.apply(this, arguments) + return Reflect.apply(makeRequest, this, arguments) } const callbackResource = new AsyncResource('bound-anonymous-fn') @@ -37,11 +37,11 @@ addHook({ name: 'tedious', versions: ['>=1.0.0'] }, tedious => { } finishCh.publish(undefined) - return cb.apply(this, arguments) + return Reflect.apply(cb, this, arguments) }, null, request) try { - return makeRequest.apply(this, arguments) + return Reflect.apply(makeRequest, this, arguments) } catch (error) { errorCh.publish(error) diff --git a/packages/datadog-instrumentations/src/url.js b/packages/datadog-instrumentations/src/url.js index 67bef7e8947..675280dcecb 100644 --- a/packages/datadog-instrumentations/src/url.js +++ b/packages/datadog-instrumentations/src/url.js @@ -11,7 +11,7 @@ const instrumentedGetters = ['host', 'origin', 'hostname'] addHook({ name: names }, function (url) { shimmer.wrap(url, 'parse', (parse) => { return function wrappedParse (input) { - const parsedValue = parse.apply(this, arguments) + const parsedValue = Reflect.apply(parse, this, arguments) if (!parseFinishedChannel.hasSubscribers) return parsedValue parseFinishedChannel.publish({ @@ -31,7 +31,7 @@ addHook({ name: names }, function (url) { if (originalDescriptor?.get) { const newDescriptor = shimmer.wrap(originalDescriptor, 'get', function (originalGet) { return function get () { - const result = originalGet.apply(this, arguments) + const result = Reflect.apply(originalGet, this, arguments) if (!urlGetterChannel.hasSubscribers) return result const context = { urlObject: this, result, property } @@ -69,7 +69,7 @@ addHook({ name: names }, function (url) { if (url.URL.parse) { shimmer.wrap(url.URL, 'parse', (parse) => { return function wrappedParse (input, base) { - const parsedValue = parse.apply(this, arguments) + const parsedValue = Reflect.apply(parse, this, arguments) if (!parseFinishedChannel.hasSubscribers) return parsedValue parseFinishedChannel.publish({ diff --git a/packages/datadog-instrumentations/src/vitest.js b/packages/datadog-instrumentations/src/vitest.js index 340fd188340..f08c92d7df4 100644 --- a/packages/datadog-instrumentations/src/vitest.js +++ b/packages/datadog-instrumentations/src/vitest.js @@ -156,7 +156,7 @@ function getTestName (task) { function getSortWrapper (sort) { return async function () { if (!testSessionFinishCh.hasSubscribers) { - return sort.apply(this, arguments) + return Reflect.apply(sort, this, arguments) } // There isn't any other async function that we seem to be able to hook into // So we will use the sort from BaseSequencer. This means that a custom sequencer @@ -262,7 +262,7 @@ function getSortWrapper (sort) { if (this.ctx.coverageProvider?.generateCoverage) { shimmer.wrap(this.ctx.coverageProvider, 'generateCoverage', generateCoverage => async function () { - const totalCodeCoverage = await generateCoverage.apply(this, arguments) + const totalCodeCoverage = await Reflect.apply(generateCoverage, this, arguments) try { testCodeCoverageLinesTotal = totalCodeCoverage.getCoverageSummary().lines.pct @@ -299,23 +299,23 @@ function getSortWrapper (sort) { await flushPromise - return exit.apply(this, arguments) + return Reflect.apply(exit, this, arguments) }) - return sort.apply(this, arguments) + return Reflect.apply(sort, this, arguments) } } function getCreateCliWrapper (vitestPackage, frameworkVersion) { shimmer.wrap(vitestPackage, 'c', oldCreateCli => function () { if (!testSessionStartCh.hasSubscribers) { - return oldCreateCli.apply(this, arguments) + return Reflect.apply(oldCreateCli, this, arguments) } sessionAsyncResource.runInAsyncScope(() => { const processArgv = process.argv.slice(2).join(' ') testSessionStartCh.publish({ command: `vitest ${processArgv}`, frameworkVersion }) }) - return oldCreateCli.apply(this, arguments) + return Reflect.apply(oldCreateCli, this, arguments) }) return vitestPackage @@ -357,7 +357,7 @@ addHook({ }) } - return onBeforeRunTask.apply(this, arguments) + return Reflect.apply(onBeforeRunTask, this, arguments) }) // `onAfterRunTask` is run after all repetitions or attempts are run @@ -381,14 +381,14 @@ addHook({ } } - return onAfterRunTask.apply(this, arguments) + return Reflect.apply(onAfterRunTask, this, arguments) }) // test start (only tests that are not marked as skip or todo) // `onBeforeTryTask` is run for every repetition and attempt of the test shimmer.wrap(VitestTestRunner.prototype, 'onBeforeTryTask', onBeforeTryTask => async function (task, retryInfo) { if (!testStartCh.hasSubscribers) { - return onBeforeTryTask.apply(this, arguments) + return Reflect.apply(onBeforeTryTask, this, arguments) } const testName = getTestName(task) let isNew = false @@ -505,16 +505,16 @@ addHook({ isQuarantined }) }) - return onBeforeTryTask.apply(this, arguments) + return Reflect.apply(onBeforeTryTask, this, arguments) }) // test finish (only passed tests) shimmer.wrap(VitestTestRunner.prototype, 'onAfterTryTask', onAfterTryTask => async function (task, { retry: retryCount }) { if (!testFinishTimeCh.hasSubscribers) { - return onAfterTryTask.apply(this, arguments) + return Reflect.apply(onAfterTryTask, this, arguments) } - const result = await onAfterTryTask.apply(this, arguments) + const result = await Reflect.apply(onAfterTryTask, this, arguments) const status = getVitestTestStatus(task, retryCount) const asyncResource = taskToAsync.get(task) @@ -617,7 +617,7 @@ addHook({ shimmer.wrap(vitestPackage, 'startTests', startTests => async function (testPaths) { let testSuiteError = null if (!testSuiteStartCh.hasSubscribers) { - return startTests.apply(this, arguments) + return Reflect.apply(startTests, this, arguments) } // From >=3.0.1, the first arguments changes from a string to an object containing the filepath const testSuiteAbsolutePath = testPaths[0]?.filepath || testPaths[0] @@ -626,7 +626,7 @@ addHook({ testSuiteAsyncResource.runInAsyncScope(() => { testSuiteStartCh.publish({ testSuiteAbsolutePath, frameworkVersion }) }) - const startTestsResponse = await startTests.apply(this, arguments) + const startTestsResponse = await Reflect.apply(startTests, this, arguments) let onFinish = null const onFinishPromise = new Promise(resolve => { diff --git a/packages/datadog-instrumentations/src/vm.js b/packages/datadog-instrumentations/src/vm.js index 9df229556fa..a61e3ea2006 100644 --- a/packages/datadog-instrumentations/src/vm.js +++ b/packages/datadog-instrumentations/src/vm.js @@ -44,6 +44,6 @@ function wrapVMMethod (original) { runScriptStartChannel.publish({ code }) } - return original.apply(this, arguments) + return Reflect.apply(original, this, arguments) } } diff --git a/packages/datadog-instrumentations/src/winston.js b/packages/datadog-instrumentations/src/winston.js index 9b9c4e811aa..e3b6320a11a 100644 --- a/packages/datadog-instrumentations/src/winston.js +++ b/packages/datadog-instrumentations/src/winston.js @@ -29,12 +29,12 @@ addHook({ name: 'winston', file: 'lib/winston/logger.js', versions: ['>=3'] }, L logCh.publish(payload) arguments[0] = payload.message } - return write.apply(this, arguments) + return Reflect.apply(write, this, arguments) } }) shimmer.wrap(Logger.prototype, 'configure', configure => function () { - const configureResponse = configure.apply(this, arguments) + const configureResponse = Reflect.apply(configure, this, arguments) // After the original `configure`, because it resets transports if (addTransport.hasSubscribers) { addTransport.publish(this) @@ -56,7 +56,7 @@ addHook({ name: 'winston', file: 'lib/winston/logger.js', versions: ['1', '2'] } function wrapMethod (method, logCh) { return function methodWithTrace () { - const result = method.apply(this, arguments) + const result = Reflect.apply(method, this, arguments) if (logCh.hasSubscribers) { for (const name in this.transports) { @@ -68,7 +68,7 @@ function wrapMethod (method, logCh) { const payload = { message: meta || {} } logCh.publish(payload) arguments[2] = payload.message - log.apply(this, arguments) + Reflect.apply(log, this, arguments) }) patched.add(transport) } diff --git a/packages/datadog-plugin-graphql/src/resolve.js b/packages/datadog-plugin-graphql/src/resolve.js index ebf8ffb59f0..7c116608206 100644 --- a/packages/datadog-plugin-graphql/src/resolve.js +++ b/packages/datadog-plugin-graphql/src/resolve.js @@ -113,7 +113,7 @@ function pathToArray (path) { function withCollapse (responsePathAsArray) { return function () { - return responsePathAsArray.apply(this, arguments) + return Reflect.apply(responsePathAsArray, this, arguments) .map(segment => typeof segment === 'number' ? '*' : segment) } } diff --git a/packages/datadog-shimmer/src/shimmer.js b/packages/datadog-shimmer/src/shimmer.js index e5f2f189381..6af98185570 100644 --- a/packages/datadog-shimmer/src/shimmer.js +++ b/packages/datadog-shimmer/src/shimmer.js @@ -32,7 +32,7 @@ function wrapFunction (original, wrapper) { let delegate = target.func const shim = function shim () { - return delegate.apply(this, arguments) + return Reflect.apply(delegate, this, arguments) } unwrappers.set(shim, () => { diff --git a/packages/dd-trace/src/appsec/iast/security-controls/index.js b/packages/dd-trace/src/appsec/iast/security-controls/index.js index 9c12805ab1c..2d6c944dc85 100644 --- a/packages/dd-trace/src/appsec/iast/security-controls/index.js +++ b/packages/dd-trace/src/appsec/iast/security-controls/index.js @@ -119,7 +119,7 @@ function resolve (path, obj, separator = '.') { function wrapSanitizer (target, secureMarks) { return shimmer.wrapFunction(target, orig => function () { - const result = orig.apply(this, arguments) + const result = Reflect.apply(orig, this, arguments) try { return addSecureMarks(result, secureMarks) @@ -145,7 +145,7 @@ function wrapInputValidator (target, parameters, secureMarks) { log.error('[ASM] Error adding Secure mark for input validator', e) } - return orig.apply(this, arguments) + return Reflect.apply(orig, this, arguments) }) } diff --git a/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js b/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js index ac95722a996..e0f12898cbd 100644 --- a/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js +++ b/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js @@ -16,7 +16,7 @@ class KafkaConsumerIastPlugin extends SourceIastPlugin { getToStringWrap (toString, iastContext, type) { return function () { - const res = toString.apply(this, arguments) + const res = Reflect.apply(toString, this, arguments) return newTaintedString(iastContext, res, undefined, type) } } diff --git a/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js b/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js index 9b446f2416e..965df0ad338 100644 --- a/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +++ b/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js @@ -100,13 +100,13 @@ function getCompileMethodFn (compileMethod) { } if (rewritten?.content) { - return compileMethod.apply(this, [rewritten.content, filename]) + return Reflect.apply(compileMethod, this, [rewritten.content, filename]) } } } catch (e) { log.error('[ASM] Error rewriting file %s', filename, e) } - return compileMethod.apply(this, [content, filename]) + return Reflect.apply(compileMethod, this, [content, filename]) } } diff --git a/packages/dd-trace/src/llmobs/sdk.js b/packages/dd-trace/src/llmobs/sdk.js index 2a6d548d656..9b41629bf53 100644 --- a/packages/dd-trace/src/llmobs/sdk.js +++ b/packages/dd-trace/src/llmobs/sdk.js @@ -156,7 +156,7 @@ class LLMObs extends NoopLLMObs { isError(maybeError) || maybeError == null ? maybeResult : maybeError ) - return scopeBoundCb.apply(this, arguments) + return Reflect.apply(scopeBoundCb, this, arguments) } } @@ -412,7 +412,7 @@ class LLMObs extends NoopLLMObs { const bound = function () { return llmobs._activate(activeSpan, null, () => { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) }) } diff --git a/packages/dd-trace/src/log/index.js b/packages/dd-trace/src/log/index.js index db3a475e120..9b0b21062b3 100644 --- a/packages/dd-trace/src/log/index.js +++ b/packages/dd-trace/src/log/index.js @@ -11,7 +11,7 @@ const memoize = func => { const cache = {} const memoized = function (key) { if (!cache[key]) { - cache[key] = func.apply(this, arguments) + cache[key] = Reflect.apply(func, this, arguments) } return cache[key] diff --git a/packages/dd-trace/src/plugins/plugin.js b/packages/dd-trace/src/plugins/plugin.js index 9d39320747d..63be4187a83 100644 --- a/packages/dd-trace/src/plugins/plugin.js +++ b/packages/dd-trace/src/plugins/plugin.js @@ -76,7 +76,7 @@ module.exports = class Plugin { const plugin = this const wrappedHandler = function () { try { - return handler.apply(this, arguments) + return Reflect.apply(handler, this, arguments) } catch (e) { logger.error('Error in plugin handler:', e) logger.info('Disabling plugin: %s', plugin.id) diff --git a/packages/dd-trace/src/plugins/util/web.js b/packages/dd-trace/src/plugins/util/web.js index 2d92c74ea91..c712eb065f0 100644 --- a/packages/dd-trace/src/plugins/util/web.js +++ b/packages/dd-trace/src/plugins/util/web.js @@ -178,7 +178,7 @@ const web = { // catch errors and apply to active span bindAndWrapMiddlewareErrors (fn, req, tracer, activeSpan) { try { - return tracer.scope().bind(fn, activeSpan).apply(this, arguments) + return Reflect.apply(tracer.scope().bind(fn, activeSpan), this, arguments) } catch (e) { web.addError(req, e) // TODO: remove when error formatting is moved to Span throw e @@ -370,7 +370,7 @@ const web = { addAllowHeaders(req, res, headers) } - return writeHead.apply(this, arguments) + return Reflect.apply(writeHead, this, arguments) } }, getContext (req) { diff --git a/packages/dd-trace/src/ritm.js b/packages/dd-trace/src/ritm.js index 71bf56952cb..32b0f85b046 100644 --- a/packages/dd-trace/src/ritm.js +++ b/packages/dd-trace/src/ritm.js @@ -61,7 +61,7 @@ function Hook (modules, options, onrequire) { try { filename = Module._resolveFilename(request, this) } catch (resolveErr) { - return _origRequire.apply(this, arguments) + return Reflect.apply(_origRequire, this, arguments) } const core = filename.indexOf(path.sep) === -1 @@ -81,7 +81,7 @@ function Hook (modules, options, onrequire) { const patched = patching[filename] if (patched) { // If it's already patched, just return it as-is. - return origRequire.apply(this, arguments) + return Reflect.apply(origRequire, this, arguments) } else { patching[filename] = true } @@ -94,7 +94,7 @@ function Hook (modules, options, onrequire) { if (moduleLoadStartChannel.hasSubscribers) { moduleLoadStartChannel.publish(payload) } - let exports = origRequire.apply(this, arguments) + let exports = Reflect.apply(origRequire, this, arguments) payload.module = exports if (moduleLoadEndChannel.hasSubscribers) { moduleLoadEndChannel.publish(payload) diff --git a/packages/dd-trace/src/scope.js b/packages/dd-trace/src/scope.js index 75cb7409066..3570e1b0502 100644 --- a/packages/dd-trace/src/scope.js +++ b/packages/dd-trace/src/scope.js @@ -42,7 +42,7 @@ class Scope { const bound = function () { return scope.activate(spanOrActive, () => { - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) }) } diff --git a/packages/dd-trace/src/tracer.js b/packages/dd-trace/src/tracer.js index 243e25575a5..af397b3e33c 100644 --- a/packages/dd-trace/src/tracer.js +++ b/packages/dd-trace/src/tracer.js @@ -102,7 +102,7 @@ class DatadogTracer extends Tracer { return function () { let optionsObj = options if (typeof optionsObj === 'function' && typeof fn === 'function') { - optionsObj = optionsObj.apply(this, arguments) + optionsObj = Reflect.apply(optionsObj, this, arguments) } const lastArgId = arguments.length - 1 @@ -113,13 +113,13 @@ class DatadogTracer extends Tracer { return tracer.trace(name, optionsObj, (span, done) => { arguments[lastArgId] = function (err) { done(err) - return scopeBoundCb.apply(this, arguments) + return Reflect.apply(scopeBoundCb, this, arguments) } - return fn.apply(this, arguments) + return Reflect.apply(fn, this, arguments) }) } else { - return tracer.trace(name, optionsObj, () => fn.apply(this, arguments)) + return tracer.trace(name, optionsObj, () => Reflect.apply(fn, this, arguments)) } } }