Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
248 lines (218 loc) · 7.77 KB
/
Copy pathindex.js
File metadata and controls
248 lines (218 loc) · 7.77 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
244
245
246
247
248
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2.0 License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.
const path = require('path')
const moduleDetailsFromPath = require('module-details-from-path')
const { fileURLToPath } = require('url')
const { MessageChannel } = require('worker_threads')
let { isBuiltin } = require('module')
if (!isBuiltin) {
isBuiltin = () => true
}
const {
importHooks,
specifiers,
toHook
} = require('./lib/register')
/**
* @param {string} specifier
* @param {string} baseDir
* @returns {boolean}
*/
function isPackageSpecifier (specifier, baseDir) {
if (process.platform === 'win32' && specifier.includes('/')) baseDir = baseDir.replaceAll(path.sep, '/')
if (baseDir.endsWith(specifier)) return true
const usingTurbopack = process.env.TURBOPACK ?? process.argv.includes('--turbo')
if (!usingTurbopack) return false
const hashSeparator = specifier.lastIndexOf('-')
return hashSeparator !== -1 && baseDir.endsWith(specifier.slice(0, hashSeparator))
}
// Every Hook instance resolves the same details for a given module load, so the
// result for the most recent URL is shared instead of being recomputed per Hook.
// The details depend only on the URL, so a stale entry can never be returned.
let lastLoadUrl
let lastDetails
/**
* @param {string} loadUrl
* @returns {{ name: string, filePath: string | undefined, baseDir: string | undefined }}
*/
function getModuleDetails (loadUrl) {
if (loadUrl === lastLoadUrl) return lastDetails
let name = loadUrl
let filePath, baseDir
if (loadUrl.startsWith('node:')) {
// Normalize builtin module name to *not* have 'node:' prefix, unless
// required, as it is for 'node:test' and some others. `module.isBuiltin`
// is available in all Node.js versions that have node:-only modules.
const unprefixed = loadUrl.slice(5)
if (isBuiltin(unprefixed)) {
name = unprefixed
}
} else if (loadUrl.startsWith('file://')) {
const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 0
try {
filePath = fileURLToPath(loadUrl)
name = filePath
} catch (e) {}
Error.stackTraceLimit = stackTraceLimit
if (filePath) {
const details = moduleDetailsFromPath(filePath)
if (details) {
name = details.name
baseDir = details.basedir
}
}
}
lastLoadUrl = loadUrl
lastDetails = { name, filePath, baseDir }
return lastDetails
}
/** @param {import('./index').HookFunction} hook */
function addHook (hook) {
importHooks.push(hook)
toHook.forEach(([name, namespace, specifier, format]) => hook(name, namespace, specifier, format))
}
function removeHook (hook) {
const index = importHooks.indexOf(hook)
if (index > -1) {
importHooks.splice(index, 1)
}
}
/**
* @param {import('./index').HookFn} hookFn
* @param {import('./index').Namespace} namespace
* @param {string} name
* @param {string | undefined} baseDir
* @param {string | undefined} format
*/
function callHookFn (hookFn, namespace, name, baseDir, format) {
const newDefault = hookFn(namespace, name, baseDir, format)
if (newDefault && newDefault !== namespace) {
// Only ESM modules that actually export `default` can have it reassigned.
// Some hooks return a value unconditionally; avoid crashing when the module
// has no default export (see issue #188).
if ('default' in namespace) {
namespace.default = newDefault
}
}
}
let sendModulesToLoader
/**
* EXPERIMENTAL
* This feature is experimental and may change in minor versions.
* **NOTE** This feature is incompatible with the {internals: true} Hook option.
*
* Creates a message channel with a port that can be used to add hooks to the
* list of exclusively included modules.
*
* This can be used to only wrap modules that are Hook'ed, however modules need
* to be hooked before they are imported.
*
* ```ts
* import { register } from 'module'
* import { Hook, createAddHookMessageChannel } from 'import-in-the-middle'
*
* const { registerOptions, waitForAllMessagesAcknowledged } = createAddHookMessageChannel()
*
* register('import-in-the-middle/hook.mjs', import.meta.url, registerOptions)
*
* Hook(['fs'], (exported, name, baseDir) => {
* // Instrument the fs module
* })
*
* // Ensure that the loader has acknowledged all the modules
* // before we allow execution to continue
* await waitForAllMessagesAcknowledged()
* ```
*/
function createAddHookMessageChannel () {
const { port1, port2 } = new MessageChannel()
let pendingAckCount = 0
let resolveFn
sendModulesToLoader = (modules) => {
pendingAckCount++
port1.postMessage(modules)
}
port1.on('message', () => {
pendingAckCount--
if (resolveFn && pendingAckCount <= 0) {
resolveFn()
}
}).unref()
function waitForAllMessagesAcknowledged () {
// This timer is to prevent the process from exiting with code 13:
// 13: Unsettled Top-Level Await.
const timer = setInterval(() => { }, 1000)
const promise = new Promise((resolve) => {
resolveFn = resolve
}).then(() => { clearInterval(timer) })
if (pendingAckCount === 0) {
resolveFn()
}
return promise
}
const addHookMessagePort = port2
const registerOptions = { data: { addHookMessagePort, include: [] }, transferList: [addHookMessagePort] }
return { registerOptions, addHookMessagePort, waitForAllMessagesAcknowledged }
}
function Hook (modules, options, hookFn) {
if ((this instanceof Hook) === false) return new Hook(modules, options, hookFn)
if (typeof modules === 'function') {
hookFn = modules
modules = null
options = null
} else if (typeof options === 'function') {
hookFn = options
options = null
}
const internals = options ? options.internals === true : false
if (sendModulesToLoader && Array.isArray(modules)) {
sendModulesToLoader(modules)
}
/**
* @param {string} loadUrl
* @param {import('./index').Namespace} namespace
* @param {string} specifier
* @param {string | undefined} format
*/
this._iitmHook = (loadUrl, namespace, specifier, format) => {
const { name, filePath, baseDir } = getModuleDetails(loadUrl)
if (modules) {
for (const matchArg of modules) {
if (filePath && matchArg === filePath) {
// abspath match
callHookFn(hookFn, namespace, filePath, undefined, format)
} else if (matchArg === name) {
if (!baseDir) {
// built-in module (or unexpected non file:// name?)
callHookFn(hookFn, namespace, name, baseDir, format)
} else if (isPackageSpecifier(specifiers.get(loadUrl), baseDir)) {
// An import of the top-level module (e.g. `import 'ioredis'`).
// Note: Slight behaviour difference from RITM. RITM uses
// `require.resolve(name)` to see if filename is the module
// main file, which will catch `require('ioredis/built/index.js')`.
// The check here will not catch `import 'ioredis/built/index.js'`.
callHookFn(hookFn, namespace, name, baseDir, format)
} else if (internals) {
const internalPath = name + path.sep + path.relative(baseDir, filePath)
callHookFn(hookFn, namespace, internalPath, baseDir, format)
}
} else if (matchArg === specifier) {
callHookFn(hookFn, namespace, specifier, baseDir, format)
}
}
} else {
callHookFn(hookFn, namespace, name, baseDir, format)
}
}
addHook(this._iitmHook)
}
Hook.prototype.unhook = function () {
removeHook(this._iitmHook)
}
module.exports = Hook
module.exports.Hook = Hook
module.exports.addHook = addHook
module.exports.removeHook = removeHook
module.exports.createAddHookMessageChannel = createAddHookMessageChannel