diff --git a/index.js b/index.js index 38a7d0d..0725304 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,11 @@ const parse = 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, @@ -124,11 +129,17 @@ function Hook (modules, options, hookFn) { this._iitmHook = (name, namespace, specifier) => { const filename = name - const isBuiltin = name.startsWith('node:') + const isNodeUrl = name.startsWith('node:') let baseDir - if (isBuiltin) { - name = name.replace(/^node:/, '') + if (isNodeUrl) { + // 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 = name.slice(5) + if (isBuiltin(unprefixed)) { + name = unprefixed + } } else { if (name.startsWith('file://')) { const stackTraceLimit = Error.stackTraceLimit diff --git a/test/hook/v18.15-node-prefixed-only.mjs b/test/hook/v18.15-node-prefixed-only.mjs new file mode 100644 index 0000000..e501d1e --- /dev/null +++ b/test/hook/v18.15-node-prefixed-only.mjs @@ -0,0 +1,12 @@ +// Test that a builtin module that must use 'node:' prefix works. +import { strictEqual } from 'assert' +import Hook from '../../index.js' + +Hook(['node:test'], (exports, name) => { + if (name === 'node:test') { + exports.skip = 'iitm was here' + } +}) + +const { skip } = await import('node:test') +strictEqual(skip, 'iitm was here')