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

Fixes #7778: Add import.meta.dirname, import.meta.filename for Node compatibility #7787

Closed
wants to merge 5 commits into from
Closed
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
18 changes: 15 additions & 3 deletions docs/api/import-meta.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ The `import.meta` object is a way for a module to access information about itsel
Bun implements the following properties.

```ts#/path/to/project/file.ts
import.meta.dir; // => "/path/to/project"
import.meta.file; // => "file.ts"
import.meta.path; // => "/path/to/project/file.ts"
import.meta.dir; // => "/path/to/project"
import.meta.dirname; // => "/path/to/project"
import.meta.file; // => "file.ts"
import.meta.filename; // => "/path/to/project/file.ts"
import.meta.path; // => "/path/to/project/file.ts"

import.meta.main; // `true` if this file is directly executed by `bun run`
// `false` otherwise
Expand All @@ -23,11 +25,21 @@ import.meta.resolveSync("zod")

---

- `import.meta.dirname`
- An alias to `import.meta.dir`

---

- `import.meta.file`
- The name of the current file, e.g. `index.tsx`

---

- `import.meta.filename`
- An alias to `import.meta.path` or `${import.meta.dir}/${import.meta.file}`

---

- `import.meta.path`
- Absolute path to the current file, e.g. `/path/to/project/index.tx`. Equivalent to `__filename` in CommonJS modules (and Node.js)

Expand Down
10 changes: 10 additions & 0 deletions packages/bun-types/globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,10 +302,20 @@ interface ImportMeta {
* Does not have a trailing slash
*/
readonly dir: string;
/**
* Absolute path to the directory containing the source file. (alias for `dir` to match Node.js)
*
* Does not have trailing slash
*/
readonly dirname: string;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think you opened this before our big @types/bun PR. but can you remove these type declarations. they should be provided by @types/node

/**
* Filename of the source file
*/
readonly file: string;
/**
* Absolute path with filename of the source file (to match Node.js)
*/
readonly filename: string;
/**
* The environment variables of the process
*
Expand Down
64 changes: 63 additions & 1 deletion src/bun.js/bindings/ImportMetaObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -417,11 +417,13 @@ JSC_DEFINE_HOST_FUNCTION(functionImportMeta__resolve,
enum class ImportMetaPropertyOffset : uint32_t {
url,
dir,
dirname,
file,
filename,
path,
require,
};
static constexpr uint32_t numberOfImportMetaProperties = 5;
static constexpr uint32_t numberOfImportMetaProperties = 7;

Zig::ImportMetaObject* ImportMetaObject::create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, const WTF::String& url)
{
Expand Down Expand Up @@ -454,6 +456,14 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_dir, (JSGlobalObject * globalO

return JSValue::encode(thisObject->dirProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_dirname, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this function

{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
return JSValue::encode(jsUndefined());

return JSValue::encode(thisObject->dirnameProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_file, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
Expand All @@ -462,6 +472,14 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_file, (JSGlobalObject * global

return JSValue::encode(thisObject->fileProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_filename, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this function

{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
return JSValue::encode(jsUndefined());

return JSValue::encode(thisObject->filenameProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_path, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
Expand Down Expand Up @@ -489,7 +507,9 @@ static const HashTableValue ImportMetaObjectPrototypeValues[] = {
{ "resolveSync"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, functionImportMeta__resolveSync, 0 } },
{ "url"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_url, 0 } },
{ "dir"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_dir, 0 } },
{ "dirname"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_dir, 0 } },
{ "file"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_file, 0 } },
{ "filename"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_filename, 0 } },
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
{ "filename"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_filename, 0 } },
{ "filename"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_path, 0 } },

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably need to check if it's readonly in node

{ "path"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_path, 0 } },
{ "require"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_require, 0 } },
{ "env"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsImportMetaObjectGetter_env, 0 } },
Expand Down Expand Up @@ -615,6 +635,28 @@ void ImportMetaObject::finishCreation(VM& vm)

init.set(jsString(init.vm, dirname));
});
this->dirnameProperty.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::JSString>::Initializer& init) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this lazy property is identical to this->dirProperty please remove it.

ImportMetaObject* meta = jsCast<ImportMetaObject*>(init.owner);

WTF::URL url = isAbsolutePath(meta->url) ? WTF::URL::fileURLWithFileSystemPath(meta->url) : WTF::URL(meta->url);
WTF::String dirname;

if (url.isValid()) {
if (url.protocolIsFile()) {
dirname = url.fileSystemPath();
} else {
dirname = url.path().toString();
}
}

if (dirname.endsWith(PLATFORM_SEP_s)) {
dirname = dirname.substring(0, dirname.length() - 1);
} else if (dirname.contains(PLATFORM_SEP)) {
dirname = dirname.substring(0, dirname.reverseFind(PLATFORM_SEP));
}

init.set(jsString(init.vm, dirname));
});
this->fileProperty.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::JSString>::Initializer& init) {
ImportMetaObject* meta = jsCast<ImportMetaObject*>(init.owner);

Expand All @@ -641,6 +683,24 @@ void ImportMetaObject::finishCreation(VM& vm)

init.set(jsString(init.vm, filename));
});
this->filenameProperty.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::JSString>::Initializer& init) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this lazy property is identical to this->pathProperty please remove it.

ImportMetaObject* meta = jsCast<ImportMetaObject*>(init.owner);

WTF::URL url = isAbsolutePath(meta->url) ? WTF::URL::fileURLWithFileSystemPath(meta->url) : WTF::URL(meta->url);
WTF::String path;

if (!url.isValid()) {
path = meta->url;
} else {
if (url.protocolIsFile()) {
path = url.fileSystemPath();
} else {
path = url.path().toString();
}
}

init.set(jsString(init.vm, path));
});
this->pathProperty.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::JSString>::Initializer& init) {
ImportMetaObject* meta = jsCast<ImportMetaObject*>(init.owner);

Expand All @@ -666,7 +726,9 @@ void ImportMetaObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
fn->requireProperty.visit(visitor);
fn->urlProperty.visit(visitor);
fn->dirProperty.visit(visitor);
fn->dirnameProperty.visit(visitor);
fn->fileProperty.visit(visitor);
fn->filenameProperty.visit(visitor);
fn->pathProperty.visit(visitor);
}

Expand Down
2 changes: 2 additions & 0 deletions src/bun.js/bindings/ImportMetaObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ class ImportMetaObject final : public JSC::JSNonFinalObject {
WTF::String url;
LazyProperty<JSObject, JSFunction> requireProperty;
LazyProperty<JSObject, JSString> dirProperty;
LazyProperty<JSObject, JSString> dirnameProperty;
LazyProperty<JSObject, JSString> urlProperty;
LazyProperty<JSObject, JSString> fileProperty;
LazyProperty<JSObject, JSString> filenameProperty;
LazyProperty<JSObject, JSString> pathProperty;

private:
Expand Down
14 changes: 13 additions & 1 deletion test/js/bun/resolve/import-meta.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as Module from "node:module";
import { join } from "node:path";
import sync from "./require-json.json";

const { path, dir } = import.meta;
const { path, dir, dirname, file, filename } = import.meta;

it("import.meta.main", () => {
const { exitCode } = spawnSync({
Expand Down Expand Up @@ -190,6 +190,18 @@ it("import.meta.dir", () => {
expect(dir.endsWith("/bun/test/js/bun/resolve")).toBe(true);
});

it("import.meta.dirname", () => {
expect(dirname.endsWith("/bun/test/js/bun/resolve")).toBe(true);
});

it("import.meta.file", () => {
expect(file.endsWith("import-meta.test.js")).toBe(true);
});

it("import.meta.filename", () => {
expect(filename.endsWith("/bun/test/js/bun/resolve/import-meta.test.js")).toBe(true);
});

it("import.meta.path", () => {
expect(path.endsWith("/bun/test/js/bun/resolve/import-meta.test.js")).toBe(true);
});
Expand Down
30 changes: 30 additions & 0 deletions test/regression/issue/07778.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { bunRunAsScript } from "harness";
import { tempDirWithFiles } from "harness";
import path from "path";

it("has import.meta behaviour that matches node.js behaviour", () => {
const fileData = `
console.log(import.meta.dir);
console.log(import.meta.dirname);
console.log(import.meta.file);
console.log(import.meta.filename);
`;

const testDir = tempDirWithFiles("07778", {
"test.mjs": fileData,
});

const { stdout, stderr } = bunRunAsScript(testDir, "test.mjs");

expect(stdout).toBeDefined();

const [dir, dirname, file, filename] = stdout.split("\n");

expect(dir).toEqual(testDir);
expect(dirname).toEqual(testDir);

expect(file).toEqual("test.mjs");
expect(filename).toEqual(path.join(testDir, "test.mjs"));

expect(stderr).toBeDefined();
});