diff options
author | 2023-06-01 18:04:09 -0700 | |
---|---|---|
committer | 2023-06-01 18:04:09 -0700 | |
commit | 3e84f18cc03a6bab898235ff2a9827b47a83aac9 (patch) | |
tree | 160b0bd3cf1b707bf68f500f0a82e85807a0fa99 /src/bun.js/bindings/CommonJSModuleRecord.cpp | |
parent | 42606d6aed323fa24b6783b24624e9f57cb9ef9d (diff) | |
download | bun-3e84f18cc03a6bab898235ff2a9827b47a83aac9.tar.gz bun-3e84f18cc03a6bab898235ff2a9827b47a83aac9.tar.zst bun-3e84f18cc03a6bab898235ff2a9827b47a83aac9.zip |
Implement `__dirname` and `__filename`, allow direct eval in CommonJS (#3164)
* Implement `__dirname` and `__filename`, allow direct eval in CommonJS
* Fixup dirname and add test
---------
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Diffstat (limited to 'src/bun.js/bindings/CommonJSModuleRecord.cpp')
-rw-r--r-- | src/bun.js/bindings/CommonJSModuleRecord.cpp | 21 |
1 files changed, 18 insertions, 3 deletions
diff --git a/src/bun.js/bindings/CommonJSModuleRecord.cpp b/src/bun.js/bindings/CommonJSModuleRecord.cpp index e3bf3a0db..a32d722d9 100644 --- a/src/bun.js/bindings/CommonJSModuleRecord.cpp +++ b/src/bun.js/bindings/CommonJSModuleRecord.cpp @@ -218,7 +218,7 @@ static Structure* internalCreateCommonJSModuleStructure( structure = structure->addPropertyTransition( vm, structure, - JSC::Identifier::fromString(vm, "fileName"_s), + JSC::Identifier::fromString(vm, "filename"_s), 0, offset); @@ -310,10 +310,15 @@ JSC::SourceCode createCommonJSModule( ? JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), source.commonJSExportsLen) : JSC::constructEmptyObject(globalObject, globalObject->objectPrototype()); - if (!globalObject->requireMap()->has(globalObject, requireMapKey)) { - globalObject->requireMap()->set(globalObject, requireMapKey, exportsObject); + auto index = sourceURL.reverseFind('/', sourceURL.length()); + JSString* dirname = jsEmptyString(vm); + JSString* filename = requireMapKey; + if (index != WTF::notFound) { + dirname = JSC::jsSubstring(globalObject, requireMapKey, 0, index); } + globalObject->requireMap()->set(globalObject, requireMapKey, exportsObject); + JSC::SourceCode inputSource( JSC::StringSourceProvider::create(sourceCodeString, JSC::SourceOrigin(WTF::URL::fileURLWithFileSystemPath(sourceURL)), @@ -344,6 +349,16 @@ JSC::SourceCode createCommonJSModule( scopeExtensionObject->putDirectOffset( vm, 2, + dirname); + + scopeExtensionObject->putDirectOffset( + vm, + 3, + filename); + + scopeExtensionObject->putDirectOffset( + vm, + 4, requireFunction); auto* executable = JSC::DirectEvalExecutable::create( |