Skip to content

feat(build): support bytes and text import attributes#4431

Merged
pi0 merged 12 commits into
mainfrom
feat/import-bytes
Jul 14, 2026
Merged

feat(build): support bytes and text import attributes#4431
pi0 merged 12 commits into
mainfrom
feat/import-bytes

Conversation

@pi0x

@pi0x pi0x commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

This PR adds support for the import bytes (stage 2.7) and import text (stage 3) proposals:

import logo from "./logo.png" with { type: "bytes" }; // Uint8Array
import readme from "./README.md" with { type: "text" }; // string

const { default: logo } = await import("./logo.png", { with: { type: "bytes" } });

As in the proposals, the file type is ignored: any file can be imported as either bytes or text.

Implementation

Rollup and rolldown both parse the syntax, but neither implements the semantics, and rolldown drops import attributes entirely before they reach plugins (resolveId only receives { isEntry, kind }). An attribute-driven resolveId would therefore only ever work on the rollup path.

Instead, a new nitro:import-attributes plugin pre-transforms the syntax into the existing raw import machinery, which gives a single code path for rollup, rolldown and vite, in both dev and prod:

  • import b from "./f.bin" with { type: "bytes" }import b from "bytes:./f.bin"
  • import("./f.bin", { with: { type: "bytes" } })import("bytes:./f.bin"), so the namespace default is the Uint8Array as specified
  • export ... from ... with { type: "..." } is handled by the same path

Parsing (oxc) and sourcemaps (MagicString) come from rolldown, already a direct dependency, so no new dependencies are added. Modules are only parsed when the attribute is actually present.

The raw plugin gains bytes: and text: prefixes next to the existing raw: one: raw: infers from the file mime, while bytes:/text: always yield a Uint8Array/string (required, as the attributes ignore the file type).

Bug fix

Resolved raw ids now carry a .js suffix. Without it, plugins matching the original extension claim the virtual module after the raw plugin has already turned it into JS: both @rollup/plugin-json (id.slice(-5) === ".json") and vite's json plugin (/\.(json|json5)($|\?)/) then fail with Could not parse JSON file. This also affected the existing raw: prefix for .json files.

Tests

Regression tests in the main fixture (/import-attributes), running against all presets:

  • static bytes import of a 256 byte file containing every byte value (verifies the base64 round trip exactly)
  • .sql imported as bytes and .json imported as text (the type-ignored cases)
  • the same .txt file dynamically imported as both bytes and text

Verified against the rollup, rolldown and vite builders, dev, and the cloudflare preset.

Notes

TypeScript implements neither proposal and types these imports by file extension, so user code still needs // @ts-ignore or a cast. This is noted in the docs.

🤖 Generated with Claude Code

Implements the import bytes and import text proposals via a pre-transform
that rewrites `with { type: "bytes" | "text" }` imports to the internal raw
prefixes, since rolldown does not expose import attributes to plugins.

Resolved raw ids now carry a `.js` suffix so that plugins matching the
original extension (`@rollup/plugin-json`, vite json, ...) no longer try to
transform them again.

https://github.com/tc39/proposal-import-bytes
https://github.com/tc39/proposal-import-text

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@pi0x
pi0x requested a review from pi0 as a code owner July 14, 2026 14:31
@vercel

vercel Bot commented Jul 14, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
nitro.build Ready Ready Preview, Comment Jul 14, 2026 4:11pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Nitro transforms bytes and text import attributes into typed virtual imports, extends raw imports with explicit binary and text prefixes, registers the new plugin, and adds documentation and integration tests.

Changes

Import attributes

Layer / File(s) Summary
Import attribute transformation
src/build/plugins/import-attributes.ts
Adds a Rollup plugin that detects static and dynamic bytes/text imports, rewrites their sources, removes import options, and emits source maps when changed.
Typed raw import resolution
src/build/plugins/raw.ts, src/build/plugins.ts
Supports raw:, bytes:, and text: virtual imports, selects binary or text output, and registers the import-attribute plugin.
Runtime coverage and usage documentation
test/fixture/server/routes/*, test/tests.ts, test/presets/vercel.test.ts, docs/1.docs/50.assets.md
Adds static, dynamic, and re-exported import coverage, validates raw JSON imports, updates Vercel route-output snapshots, and documents syntax, bundling behavior, prefixes, and TypeScript limitations.

Estimated code review effort: 3 (Moderate) | ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title follows conventional commits and clearly summarizes the main change to build support for bytes/text import attributes.
Description check ✅ Passed The description is directly related to the changeset and accurately explains the new import-attributes support and related implementation details.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/import-bytes

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/build/plugins/raw.ts`:
- Around line 51-58: Restore the this.addWatchFile(path) call in the handler
method after parseRawId(id) and before reading the file, so raw text and binary
assets are tracked for watch-mode updates. Leave the HELPER_ID branch and
existing fsp.readFile behavior unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a046af3a-d77c-4cad-b27d-dc7483f8c53a

📥 Commits

Reviewing files that changed from the base of the PR and between 05bf1c3 and acf8b4f.

⛔ Files ignored due to path filters (1)
  • test/fixture/server/files/bytes.bin is excluded by !**/*.bin
📒 Files selected for processing (6)
  • docs/1.docs/50.assets.md
  • src/build/plugins.ts
  • src/build/plugins/import-attributes.ts
  • src/build/plugins/raw.ts
  • test/fixture/server/routes/import-attributes.ts
  • test/tests.ts

Comment thread src/build/plugins/raw.ts Outdated
- warn instead of silently skipping when oxc cannot parse a module
- lazily import rolldown, matching the oxc and route-meta plugins
- derive raw prefix regexes from a single list of types
- test `raw:` json imports and `export ... from ... with { type }`

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
src/build/plugins/raw.ts (1)

51-54: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Restore this.addWatchFile(path) for raw assets.

The plugin reads the underlying file through a synthetic virtual:nitro:* module, meaning the bundler won't track the original source asset automatically. By leaving this commented out, edits to the raw text or binary inputs won't trigger a rebuild and can stay stale in watch mode.

🐛 Proposed fix
         const { path, binary } = parseRawId(id);
-        // this.addWatchFile(path);
+        this.addWatchFile(path);
         return fsp.readFile(path, binary ? "binary" : "utf8");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/build/plugins/raw.ts` around lines 51 - 54, Restore the
this.addWatchFile(path) call in the raw asset loading hook immediately after
parseRawId(id) and before fsp.readFile, so both text and binary source files are
tracked for watch-mode rebuilds.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@src/build/plugins/raw.ts`:
- Around line 51-54: Restore the this.addWatchFile(path) call in the raw asset
loading hook immediately after parseRawId(id) and before fsp.readFile, so both
text and binary source files are tracked for watch-mode rebuilds.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 18cb395b-18fb-4447-be9d-b728e21d07f5

📥 Commits

Reviewing files that changed from the base of the PR and between acf8b4f and 57d7f34.

📒 Files selected for processing (7)
  • src/build/plugins.ts
  • src/build/plugins/import-attributes.ts
  • src/build/plugins/raw.ts
  • test/fixture/server/routes/_import-attributes-reexport.ts
  • test/fixture/server/routes/import-attributes.ts
  • test/fixture/server/routes/raw.ts
  • test/tests.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/build/plugins.ts
  • test/fixture/server/routes/import-attributes.ts
  • test/tests.ts
  • src/build/plugins/import-attributes.ts

Raw ids end with a `.js` suffix, so the import attributes plugin matched the
file contents loaded by the raw plugin and rewrote the attribute syntax inside
source files imported as text. Exclude the raw plugin ids from its transform.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Use the oxc ESTree types from rolldown instead of `any`, remove the
dynamic import options via its own span, and re-check the id filter in
the handler fallback.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Windows runners check out with autocrlf, so a `text:` or `raw:` import of
`test.json` returned CRLF and failed the exact-content assertions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@pkg-pr-new

pkg-pr-new Bot commented Jul 14, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/nitro@4431

commit: ee68c12

pi0 and others added 2 commits July 14, 2026 15:41
Enable watching of raw-imported files, skip query strings and external
resolutions, and tolerate builders without hook filter support.

Co-Authored-By: Claude Fable 5 <[email protected]>
Exclude raw modules from `@rollup/plugin-replace` and drop its chunk-level
`renderChunk` pass, which rewrote keys like `import.meta.*` inside imported
file contents after inlining (breaking the syntax with quoted values). Also
skip transpiling raw modules in the oxc plugin.

Co-Authored-By: Claude Fable 5 <[email protected]>
pi0 and others added 2 commits July 14, 2026 15:57
The `with { ... }` clause has no AST node, so its closing brace was taken as
the first `}` after the last attribute. A `}` inside a comment was mistaken
for it, silently emitting broken code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Returning null left the prefixed id unresolved, which the bundler then
treated as an external import, silently producing a broken bundle.

Co-Authored-By: Claude Fable 5 <[email protected]>
Virtual modules (`nitro.vfs`, other plugins) have no file behind them, so
`load` read them from disk and failed with a bare ENOENT. Inline their
rendered source instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
@pi0
pi0 merged commit c6e6168 into main Jul 14, 2026
13 checks passed
@pi0
pi0 deleted the feat/import-bytes branch July 14, 2026 16:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants