fix replacing node:module._resolveFilename not passing the parent module (#7993)

* fix replacing node:module._resolveFilename

* add a test
This commit is contained in:
Meghan Denny
2024-01-05 00:36:07 -08:00
committed by GitHub
parent 39ab26a663
commit 89ec2fcb35
6 changed files with 57 additions and 14 deletions

View File

@@ -188,18 +188,24 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire,
if (val.startsWith("file://"_s)) {
WTF::URL url(val);
if (!url.isValid()) {
throwTypeError(globalObject, scope, makeString("createRequire() was given an invalid URL '"_s, url.string(), "'"_s));;
throwTypeError(globalObject, scope,
makeString("createRequire() was given an invalid URL '"_s,
url.string(), "'"_s));
;
RELEASE_AND_RETURN(scope, JSValue::encode({}));
}
if (!url.protocolIsFile()) {
throwTypeError(globalObject, scope, "createRequire() does not support non-file URLs"_s);
throwTypeError(globalObject, scope,
"createRequire() does not support non-file URLs"_s);
RELEASE_AND_RETURN(scope, JSValue::encode({}));
}
val = url.fileSystemPath();
}
RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::jsUndefined()));
RELEASE_AND_RETURN(scope, JSValue::encode(Bun::JSCommonJSModule::createBoundRequireFunction(vm, globalObject, val)));
RELEASE_AND_RETURN(
scope, JSValue::encode(Bun::JSCommonJSModule::createBoundRequireFunction(
vm, globalObject, val)));
}
extern "C" JSC::EncodedJSValue Resolver__nodeModulePathsForJS(JSGlobalObject *,
CallFrame *);
@@ -246,6 +252,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName,
}
default: {
JSC::JSValue moduleName = callFrame->argument(0);
JSC::JSValue fromValue = callFrame->argument(1);
if (moduleName.isUndefinedOrNull()) {
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
@@ -255,9 +262,26 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName,
return JSC::JSValue::encode(JSC::JSValue{});
}
if (
// fast path: it's a real CommonJS module object.
auto *cjs = jsDynamicCast<Bun::JSCommonJSModule *>(fromValue)) {
fromValue = cjs->id();
} else if
// slow path: userland code did something weird. lets let them do that
// weird thing.
(fromValue.isObject()) {
if (auto idValue = fromValue.getObject()->getIfPropertyExists(
globalObject, Identifier::fromString(vm, "filename"_s))) {
if (idValue.isString()) {
fromValue = idValue;
}
}
}
auto result =
Bun__resolveSync(globalObject, JSC::JSValue::encode(moduleName),
JSValue::encode(callFrame->argument(1)), false);
JSValue::encode(fromValue), false);
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
if (!JSC::JSValue::decode(result).isString()) {