aspect-build / aspect-build/rules_js

[FR]: Relative runfiles resolution

Open
#1,257 2 comments 0 reactions 0 assignees View on GitHub
enhancement need: discussion need: investigation
Dominant language
Starlark
Stars
378
Forks
183
Avg merge
1d 9h
Merged PRs (30d)
32

Description

### What is the current behavior?

Every Bazel program eventually needs to look up data in runfiles. Currently this done in JavaScript by either:
* Accessing the `${RUNFILES}` environment variable like `${RUNFILES}/wksp/path/to/file.txt`.
* Using `@bazel/runfiles`. I think this technically works with `@aspect_rules_js`, though I've had trouble with it in the past.

### Describe the feature

It would be very cool to have an API which works with relative paths like other JavaScript features such as `import`. This can be achieved with `import.meta` like so:

```typescript
// wksp/path/to/script.mjs

import { promises as fs } from 'fs';
import { runfile } from '...';

// Returns `/.../wksp/path/to/file.txt`.
const filePath = runfile('./file.txt', import.meta);

const contents = await fs.readFile(filePath, 'utf8');
console.log(contents);
```

I'm not sure if `@aspect_rules_js` exposes any other JavaScript APIs, but I think this would be a useful and elegant one. It does require `import.meta` which necessitates either native ESM execution or a bundler which supports it. Exposing the absolute path to the runfile probably isn't ideal, since it leaks some information from outside the sandbox. Another approach would be to return a file path relative to the CWD, that way it could still be passed directly into APIs like `fs.readFile` and work as expected.

The actual implementation probably isn't too involved. [I did my own version of this pattern](https://github.com/dgp1130/rules_prerender/blob/3b6bbd4cfdf89aced79ce711e3e24845fb64a14a/packages/preact/index.mts#L94) with a Preact element ``. We could probably copy most of that implementation.

I can't think of any other JS APIs for `@aspect_rules_js` and I know from experience that pairing a Bazel ruleset with an NPM package can be quite challenging, so I can understand if this is out of scope. I just think it's a cool and elegant idea which is worth considering adopting directly into the ruleset.

Contributor guide

Open the contributing guide

Research direction

Review @bazel/runfiles and the linked packages/preact/index.mts implementation first, then inspect how @aspect_rules_js currently exposes runfiles. Resolve the API shape, import.meta requirements, and sandbox-safe path behavior; done means the relative runfiles API is implemented and its proposed usage is covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
build-system
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.