Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor node:module #14227

Merged
merged 9 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmake/targets/BuildBun.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ set(BUN_OBJECT_LUT_SOURCES
${CWD}/src/bun.js/bindings/BunProcess.cpp
${CWD}/src/bun.js/bindings/ProcessBindingConstants.cpp
${CWD}/src/bun.js/bindings/ProcessBindingNatives.cpp
${CWD}/src/bun.js/modules/NodeModuleModule.cpp
)

set(BUN_OBJECT_LUT_OUTPUTS
Expand All @@ -407,8 +408,10 @@ set(BUN_OBJECT_LUT_OUTPUTS
${CODEGEN_PATH}/BunProcess.lut.h
${CODEGEN_PATH}/ProcessBindingConstants.lut.h
${CODEGEN_PATH}/ProcessBindingNatives.lut.h
${CODEGEN_PATH}/NodeModuleModule.lut.h
)


macro(WEBKIT_ADD_SOURCE_DEPENDENCIES _source _deps)
set(_tmp)
get_source_file_property(_tmp ${_source} OBJECT_DEPENDS)
Expand Down
11 changes: 5 additions & 6 deletions src/bun.js/bindings/CommonJSModuleRecord.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,11 @@ void JSCommonJSModule::toSyntheticSource(JSC::JSGlobalObject* globalObject,
populateESMExports(globalObject, result, exportNames, exportValues, this->ignoreESModuleAnnotation);
}

void JSCommonJSModule::setExportsObject(JSC::JSValue exportsObject)
{
this->putDirect(vm(), JSC::PropertyName(clientData(vm())->builtinNames().exportsPublicName()), exportsObject, 0);
}

JSValue JSCommonJSModule::exportsObject()
{
return this->get(globalObject(), JSC::PropertyName(clientData(vm())->builtinNames().exportsPublicName()));
Expand Down Expand Up @@ -1004,12 +1009,6 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionRequireCommonJS, (JSGlobalObject * lexicalGlo
WTF::String specifier = specifierValue.toWTFString(globalObject);
RETURN_IF_EXCEPTION(throwScope, {});

// Special-case for "process" to just return the process object directly.
if (UNLIKELY(specifier == "process"_s || specifier == "node:process"_s)) {
jsCast<JSCommonJSModule*>(callframe->argument(1))->putDirect(vm, builtinNames(vm).exportsPublicName(), globalObject->processObject(), 0);
return JSValue::encode(globalObject->processObject());
}

WTF::String referrer = thisObject->id().toWTFString(globalObject);
RETURN_IF_EXCEPTION(throwScope, {});

Expand Down
5 changes: 3 additions & 2 deletions src/bun.js/bindings/CommonJSModuleRecord.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class JSCommonJSModule final : public JSC::JSDestructibleObject {
JSC::MarkedArgumentBuffer& exportValues);

JSValue exportsObject();
void setExportsObject(JSC::JSValue exportsObject);
JSValue id();

bool load(JSC::VM& vm, Zig::GlobalObject* globalObject, WTF::NakedPtr<JSC::Exception>&);
Expand Down Expand Up @@ -157,7 +158,7 @@ class RequireResolveFunctionPrototype final : public JSC::JSNonFinalObject {
using Base = JSC::JSNonFinalObject;

static RequireResolveFunctionPrototype* create(JSC::JSGlobalObject* globalObject);
static Structure* createStructure(VM& vm, JSC::JSGlobalObject* globalObject);
static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject);

DECLARE_INFO;

Expand All @@ -183,7 +184,7 @@ class RequireFunctionPrototype final : public JSC::JSNonFinalObject {
using Base = JSC::JSNonFinalObject;

static RequireFunctionPrototype* create(JSC::JSGlobalObject* globalObject);
static Structure* createStructure(VM& vm, JSC::JSGlobalObject* globalObject);
static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject);

DECLARE_INFO;

Expand Down
38 changes: 20 additions & 18 deletions src/bun.js/bindings/ImportMetaObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -303,26 +303,28 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo

if (!isESM) {
if (LIKELY(globalObject)) {
auto overrideHandler = globalObject->m_nodeModuleOverriddenResolveFilename.get();
if (UNLIKELY(overrideHandler)) {
ASSERT(overrideHandler->isCallable());
JSValue parentModuleObject = globalObject->requireMap()->get(globalObject, from);

JSValue parentID = jsUndefined();
if (auto* parent = jsDynamicCast<Bun::JSCommonJSModule*>(parentModuleObject)) {
parentID = parent->id();
} else {
parentID = from;
}
if (UNLIKELY(globalObject->hasOverridenModuleResolveFilenameFunction)) {
auto overrideHandler = jsCast<JSObject*>(globalObject->m_moduleResolveFilenameFunction.getInitializedOnMainThread(globalObject));
if (UNLIKELY(overrideHandler)) {
ASSERT(overrideHandler->isCallable());
JSValue parentModuleObject = globalObject->requireMap()->get(globalObject, from);

JSValue parentID = jsUndefined();
if (auto* parent = jsDynamicCast<Bun::JSCommonJSModule*>(parentModuleObject)) {
parentID = parent->id();
} else {
parentID = from;
}

MarkedArgumentBuffer args;
args.append(moduleName);
args.append(parentModuleObject);
auto parentIdStr = parentID.toWTFString(globalObject);
auto bunStr = Bun::toString(parentIdStr);
args.append(jsBoolean(Bun__isBunMain(lexicalGlobalObject, &bunStr)));
MarkedArgumentBuffer args;
args.append(moduleName);
args.append(parentModuleObject);
auto parentIdStr = parentID.toWTFString(globalObject);
auto bunStr = Bun::toString(parentIdStr);
args.append(jsBoolean(Bun__isBunMain(lexicalGlobalObject, &bunStr)));

return JSValue::encode(JSC::call(lexicalGlobalObject, overrideHandler, JSC::getCallData(overrideHandler), parentModuleObject, args));
return JSValue::encode(JSC::call(lexicalGlobalObject, overrideHandler, JSC::getCallData(overrideHandler), parentModuleObject, args));
}
}
}
}
Expand Down
14 changes: 12 additions & 2 deletions src/bun.js/bindings/ModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -517,14 +517,24 @@ JSValue fetchCommonJSModule(

auto tag = res->result.value.tag;
switch (tag) {
case SyntheticModuleType::NodeModule: {
target->setExportsObject(globalObject->m_nodeModuleConstructor.getInitializedOnMainThread(globalObject));
target->hasEvaluated = true;
RELEASE_AND_RETURN(scope, target);
}
case SyntheticModuleType::NodeProcess: {
target->setExportsObject(globalObject->processObject());
target->hasEvaluated = true;
RELEASE_AND_RETURN(scope, target);
}
// Generated native module cases
#define CASE(str, name) \
case SyntheticModuleType::name: { \
target->evaluate(globalObject, specifier->toWTFString(BunString::ZeroCopy), generateNativeModule_##name); \
RETURN_IF_EXCEPTION(scope, {}); \
RELEASE_AND_RETURN(scope, target); \
}
BUN_FOREACH_NATIVE_MODULE(CASE)
BUN_FOREACH_CJS_NATIVE_MODULE(CASE)
#undef CASE

case SyntheticModuleType::ESM: {
Expand Down Expand Up @@ -746,7 +756,7 @@ static JSValue fetchESMSourceCode(
auto source = JSC::SourceCode(JSC::SyntheticSourceProvider::create(generateNativeModule_##name, JSC::SourceOrigin(), WTFMove(moduleKey))); \
return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); \
}
BUN_FOREACH_NATIVE_MODULE(CASE)
BUN_FOREACH_ESM_NATIVE_MODULE(CASE)
#undef CASE

// CommonJS modules from src/js/*
Expand Down
9 changes: 7 additions & 2 deletions src/bun.js/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
#include "ErrorCode.h"
#include "v8/shim/GlobalInternals.h"
#include "EventLoopTask.h"
#include "NodeModuleModule.h"
#include <JavaScriptCore/JSCBytecodeCacheVersion.h>

#if ENABLE(REMOTE_INSPECTOR)
Expand Down Expand Up @@ -2685,6 +2686,8 @@ void GlobalObject::finishCreation(VM& vm)

m_commonStrings.initialize();

Bun::addNodeModuleConstructorProperties(vm, this);

m_JSDOMFileConstructor.initLater(
[](const Initializer<JSObject>& init) {
JSObject* fileConstructor = Bun::createJSDOMFileConstructor(init.vm, init.owner);
Expand Down Expand Up @@ -3602,7 +3605,6 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
visitor.append(thisObject->m_readableStreamToJSON);
visitor.append(thisObject->m_readableStreamToText);
visitor.append(thisObject->m_readableStreamToFormData);
visitor.append(thisObject->m_nodeModuleOverriddenResolveFilename);

visitor.append(thisObject->m_nextTickQueue);
visitor.append(thisObject->m_errorConstructorPrepareStackTraceValue);
Expand All @@ -3612,6 +3614,8 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)

visitor.append(thisObject->m_currentNapiHandleScopeImpl);

thisObject->m_moduleResolveFilenameFunction.visit(visitor);
thisObject->m_nodeModuleConstructor.visit(visitor);
thisObject->m_asyncBoundFunctionStructure.visit(visitor);
thisObject->m_bunObject.visit(visitor);
thisObject->m_cachedNodeVMGlobalObjectStructure.visit(visitor);
Expand Down Expand Up @@ -3965,7 +3969,8 @@ JSC::JSInternalPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* j
ASSERT(startRefCount == moduleName.impl()->refCount());
if (!resolved.success) {
throwException(scope, resolved.result.err, globalObject);
return JSC::JSInternalPromise::rejectedPromiseWithCaughtException(globalObject, scope);
auto* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
return promise->rejectWithCaughtException(globalObject, scope);
}

JSC::Identifier resolvedIdentifier;
Expand Down
7 changes: 4 additions & 3 deletions src/bun.js/bindings/ZigGlobalObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,8 @@ class GlobalObject : public Bun::GlobalScope {
mutable WriteBarrier<JSFunction> m_readableStreamToText;
mutable WriteBarrier<JSFunction> m_readableStreamToFormData;

// This is set when doing `require('module')._resolveFilename = ...`
// a hack used by Next.js to inject their versions of webpack and react
mutable WriteBarrier<JSFunction> m_nodeModuleOverriddenResolveFilename;
LazyProperty<JSGlobalObject, JSCell> m_moduleResolveFilenameFunction;
LazyProperty<JSGlobalObject, JSObject> m_nodeModuleConstructor;

mutable WriteBarrier<Unknown> m_nextTickQueue;

Expand Down Expand Up @@ -586,6 +585,8 @@ class GlobalObject : public Bun::GlobalScope {
LazyProperty<JSGlobalObject, JSObject> m_performanceObject;
LazyProperty<JSGlobalObject, JSObject> m_processObject;

bool hasOverridenModuleResolveFilenameFunction = false;

private:
DOMGuardedObjectSet m_guardedObjects WTF_GUARDED_BY_LOCK(m_gcLock);
WebCore::SubtleCrypto* m_subtleCrypto = nullptr;
Expand Down
Loading
Loading