diff --git a/hook.js b/hook.js index 6f0adbd..b5d72f5 100644 --- a/hook.js +++ b/hook.js @@ -4,6 +4,7 @@ const { URL } = require('url') const { inspect } = require('util') +const { isIdentifierName } = require('@babel/helper-validator-identifier') const { builtinModules } = require('module') const specifiers = new Map() const isWin = process.platform === 'win32' @@ -200,6 +201,10 @@ async function processModule ({ srcUrl, context, parentGetSource, parentResolve, const setters = new Map() const addSetter = (name, setter, isStarExport = false) => { + if (!isIdentifierName(name)) { + throw new Error(`'${name}' export is not a valid identifier name`) + } + if (setters.has(name)) { if (isStarExport) { // If there's already a matching star export, delete it @@ -380,7 +385,8 @@ function createHook (meta) { } } - async function getSource (url, context, parentGetSource) { + // For Node.js 16.12.0 and higher. + async function load (url, context, parentGetSource) { if (hasIitm(url)) { const realUrl = deleteIitm(url) @@ -392,6 +398,8 @@ function createHook (meta) { parentResolve: cachedResolve }) return { + shortCircuit: true, + format: 'module', source: ` import { register } from '${iitmURL}' import * as namespace from ${JSON.stringify(realUrl)} @@ -432,20 +440,6 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea return parentGetSource(url, context, parentGetSource) } - // For Node.js 16.12.0 and higher. - async function load (url, context, parentLoad) { - if (hasIitm(url)) { - const { source } = await getSource(url, context, parentLoad) - return { - source, - shortCircuit: true, - format: 'module' - } - } - - return parentLoad(url, context, parentLoad) - } - if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) { return { initialize, load, resolve } } else { @@ -453,7 +447,7 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea initialize, load, resolve, - getSource, + getSource: load, getFormat (url, context, parentGetFormat) { if (hasIitm(url)) { return { diff --git a/package.json b/package.json index 424b4e1..cfa5b8c 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "acorn": "^8.8.2", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", - "module-details-from-path": "^1.0.3" + "module-details-from-path": "^1.0.3", + "@babel/helper-validator-identifier": "^7.24.7" } } diff --git a/test/fixtures/invalid-identifier.js b/test/fixtures/invalid-identifier.js new file mode 100644 index 0000000..c604f80 --- /dev/null +++ b/test/fixtures/invalid-identifier.js @@ -0,0 +1 @@ +exports['one.two'] = () => console.log('b') diff --git a/test/hook/invalid-identifier.mjs b/test/hook/invalid-identifier.mjs new file mode 100644 index 0000000..6f4acf0 --- /dev/null +++ b/test/hook/invalid-identifier.mjs @@ -0,0 +1,4 @@ +import * as lib from '../fixtures/invalid-identifier.js' +import { strictEqual } from 'assert' + +strictEqual(typeof lib['one.two'], 'function')