-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathritm.js
More file actions
243 lines (203 loc) · 7.3 KB
/
ritm.js
File metadata and controls
243 lines (203 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
'use strict'
const path = require('path')
const fs = require('fs')
const Module = require('module')
const dc = require('dc-polyfill')
const parse = require('../../../vendor/dist/module-details-from-path')
const { isRelativeRequire } = require('../../datadog-instrumentations/src/helpers/shared-utils')
const { getEnvironmentVariable, getValueFromEnvSources } = require('./config/helper')
const origRequire = Module.prototype.require
// derived from require-in-the-middle@3 with tweaks
module.exports = Hook
let moduleHooks = Object.create(null)
let cache = Object.create(null)
let patching = Object.create(null)
let patchedRequire = null
const moduleLoadStartChannel = dc.channel('dd-trace:moduleLoadStart')
const moduleLoadEndChannel = dc.channel('dd-trace:moduleLoadEnd')
function stripNodePrefix (name) {
if (typeof name !== 'string') return name
return name.startsWith('node:') ? name.slice(5) : name
}
const builtinModules = new Set(Module.builtinModules.map(stripNodePrefix))
function isBuiltinModuleName (name) {
if (typeof name !== 'string') return false
return builtinModules.has(stripNodePrefix(name))
}
function normalizeModuleName (name) {
if (typeof name !== 'string') return name
const stripped = stripNodePrefix(name)
return builtinModules.has(stripped) ? stripped : name
}
/**
* @overload
* @param {string[]} modules list of modules to hook into
* @param {object} options hook options
* @param {Function} onrequire callback to be executed upon encountering module
*/
/**
* @overload
* @param {string[]} modules list of modules to hook into
* @param {Function} onrequire callback to be executed upon encountering module
*/
function Hook (modules, options, onrequire) {
if (!(this instanceof Hook)) return new Hook(modules, options, onrequire)
if (typeof options === 'function') {
onrequire = options
options = {}
}
modules ??= []
options ??= {}
this.modules = modules
this.options = options
this.onrequire = onrequire
if (Array.isArray(modules)) {
for (const mod of modules) {
const hooks = moduleHooks[mod]
if (hooks) {
hooks.push(onrequire)
} else {
moduleHooks[mod] = [onrequire]
}
}
}
if (patchedRequire) return
const _origRequire = Module.prototype.require
patchedRequire = Module.prototype.require = function (request) {
/*
If resolving the filename for a `require(...)` fails, defer to the wrapped
require implementation rather than failing right away. This allows a
possibly monkey patched `require` to work.
*/
let filename
try {
// @ts-expect-error - Module._resolveFilename is not typed
filename = Module._resolveFilename(request, this)
} catch {
return _origRequire.apply(this, arguments)
}
const builtin = isBuiltinModuleName(filename)
const moduleId = builtin ? normalizeModuleName(filename) : filename
let name, basedir, hooks
// return known patched modules immediately
if (cache[moduleId]) {
// require.cache was potentially altered externally
const cacheEntry = require.cache[filename]
if (cacheEntry && cacheEntry.exports !== cache[filename].original) {
return cacheEntry.exports
}
return cache[moduleId].exports
}
// Check if this module has a patcher in-progress already.
// Otherwise, mark this module as patching in-progress.
const patched = patching[moduleId]
if (patched) {
// If it's already patched, just return it as-is.
return origRequire.apply(this, arguments)
}
patching[moduleId] = true
const payload = {
filename,
request,
}
if (moduleLoadStartChannel.hasSubscribers) {
moduleLoadStartChannel.publish(payload)
}
let exports = origRequire.apply(this, arguments)
payload.module = exports
if (moduleLoadEndChannel.hasSubscribers) {
moduleLoadEndChannel.publish(payload)
exports = payload.module
}
// The module has already been loaded,
// so the patching mark can be cleaned up.
delete patching[moduleId]
if (builtin) {
hooks = moduleHooks[moduleId]
if (!hooks) return exports // abort if module name isn't on whitelist
name = moduleId
} else {
const inAWSLambda = getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') !== undefined
const hasLambdaHandler = getValueFromEnvSources('DD_LAMBDA_HANDLER') !== undefined
const segments = filename.split(path.sep)
const filenameFromNodeModule = segments.includes('node_modules')
// decide how to assign the stat
// first case will only happen when patching an AWS Lambda Handler
const stat = inAWSLambda && hasLambdaHandler && !filenameFromNodeModule ? { name: filename } : parse(filename)
if (stat) {
name = stat.name
basedir = stat.basedir
hooks = moduleHooks[name]
if (!hooks) return exports // abort if module name isn't on whitelist
// figure out if this is the main module file, or a file inside the module
// @ts-expect-error - Module._resolveLookupPaths is meant to be internal and is not typed
const paths = Module._resolveLookupPaths(name, this, true)
if (!paths) {
// abort if _resolveLookupPaths return null
return exports
}
let res
try {
// @ts-expect-error - Module._findPath is meant to be internal and is not typed
res = Module._findPath(name, [basedir, ...paths])
} catch {
// case where the file specified in package.json "main" doesn't exist
// in this case, the file is treated as module-internal
}
if (!res || res !== filename) {
// this is a module-internal file
// use the module-relative path to the file, prefixed by original module name
name = name + path.sep + path.relative(basedir, filename)
}
} else {
if (isRelativeRequire(request) && moduleHooks[request]) {
hooks = moduleHooks[request]
name = request
basedir = findProjectRoot(filename)
}
if (!hooks) return exports
}
}
// ensure that the cache entry is assigned a value before calling
// onrequire, in case calling onrequire requires the same module.
cache[moduleId] = { exports }
cache[moduleId].original = exports
for (const hook of hooks) {
cache[moduleId].exports = hook(cache[moduleId].exports, name, basedir)
}
return cache[moduleId].exports
}
}
/**
* Reset the Ritm hook. This is used to reset the hook after a test.
* TODO: Remove this and instead use proxyquire to reset the hook.
*/
Hook.reset = function () {
Module.prototype.require = origRequire
patchedRequire = null
patching = Object.create(null)
cache = Object.create(null)
moduleHooks = Object.create(null)
}
function findProjectRoot (startDir) {
let dir = startDir
while (!fs.existsSync(path.join(dir, 'package.json'))) {
const parent = path.dirname(dir)
if (parent === dir) break
dir = parent
}
return dir
}
Hook.prototype.unhook = function () {
for (const mod of this.modules) {
const hooks = (moduleHooks[mod] || []).filter(hook => hook !== this.onrequire)
if (hooks.length > 0) {
moduleHooks[mod] = hooks
} else {
delete moduleHooks[mod]
}
}
if (Object.keys(moduleHooks).length === 0) {
Hook.reset()
}
}