Skip to content

Commit c6e6168

Browse files
authored
feat(build): support bytes and text import attributes (#4431)
1 parent 05bf1c3 commit c6e6168

13 files changed

Lines changed: 462 additions & 27 deletions

File tree

‎.gitattributes‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1+
# Files imported verbatim (`raw:`, `bytes:`, `text:`) must not have their line endings rewritten
12
*.txt text eol=lf
3+
*.json text eol=lf
4+
*.sql text eol=lf
5+
*.bin binary

‎docs/1.docs/50.assets.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,39 @@ export default defineHandler(async (event) => {
170170

171171
> [!TIP]
172172
> During development, server assets are read directly from the filesystem using the `fs` unstorage driver. In production, they are bundled into the server as lazy imports with pre-computed metadata (MIME type, ETag, modification time).
173+
174+
## Importing Files
175+
176+
Any file can be imported with a `type` import attribute. Its contents are inlined into the server bundle as a `Uint8Array` with [`type: "bytes"`](https://github.com/tc39/proposal-import-bytes) or as a UTF-8 `string` with [`type: "text"`](https://github.com/tc39/proposal-import-text):
177+
178+
```ts [routes/logo.ts]
179+
import { defineHandler } from "nitro";
180+
181+
import logo from "./logo.png" with { type: "bytes" }; // Uint8Array
182+
import readme from "./README.md" with { type: "text" }; // string
183+
184+
export default defineHandler(() => {
185+
return new Response(logo, { headers: { "content-type": "image/png" } });
186+
});
187+
```
188+
189+
The file type is ignored: any file can be imported as either bytes or text.
190+
191+
Dynamic imports are supported as well:
192+
193+
```ts
194+
const { default: logo } = await import("./logo.png", { with: { type: "bytes" } });
195+
```
196+
197+
Alternatively, the `raw:` prefix imports a file as a `string` (for text files, based on the file type) or a `Uint8Array` (for binary files):
198+
199+
```ts
200+
import readme from "raw:./README.md"; // string
201+
import logo from "raw:./logo.png"; // Uint8Array
202+
```
203+
204+
> [!NOTE]
205+
> Imported files are inlined into the server bundle (base64 encoded for binary files). Prefer [server assets](#server-assets) for larger files.
206+
207+
> [!NOTE]
208+
> TypeScript does not support the `bytes` and `text` attributes yet. Until then, imports of unknown file types need a `// @ts-ignore` comment.

‎src/build/plugins.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import { routeMeta } from "./plugins/route-meta.ts";
99
import { serverMain } from "./plugins/server-main.ts";
1010
import { virtual, virtualDeps } from "./plugins/virtual.ts";
1111
import { sourcemapMinify } from "./plugins/sourcemap-min.ts";
12-
import { raw } from "./plugins/raw.ts";
12+
import { raw, RESOLVED_RE as rawModulesRE } from "./plugins/raw.ts";
13+
import { importAttributes } from "./plugins/import-attributes.ts";
1314
import { externals } from "./plugins/externals.ts";
1415

1516
export async function baseBuildPlugins(nitro: Nitro, base: BaseBuildConfig) {
@@ -35,20 +36,25 @@ export async function baseBuildPlugins(nitro: Nitro, base: BaseBuildConfig) {
3536
plugins.push(serverMain(nitro));
3637

3738
// Raw Imports
38-
plugins.push(raw());
39+
plugins.push(await importAttributes(), raw());
3940

4041
// Route meta
4142
if (nitro.options.experimental.openAPI) {
4243
plugins.push(await routeMeta(nitro));
4344
}
4445

4546
// Replace
46-
plugins.push(
47-
(replace as unknown as typeof replace.default)({
48-
preventAssignment: true,
49-
values: base.replacements,
50-
})
51-
);
47+
const replacePlugin = (replace as unknown as typeof replace.default)({
48+
preventAssignment: true,
49+
values: base.replacements,
50+
// Raw modules hold file contents as string literals; replacing inside them
51+
// corrupts the content (and can break the syntax with quoted values)
52+
exclude: rawModulesRE,
53+
});
54+
// The plugin re-applies replacements on whole chunks, where raw module contents
55+
// can no longer be excluded by id. All replaceable code goes through `transform`.
56+
delete replacePlugin.renderChunk;
57+
plugins.push(replacePlugin);
5258

5359
// Externals (require Node.js compatible resolution)
5460
if (nitro.options.node && nitro.options.noExternals !== true) {
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import type { Plugin } from "rollup";
2+
import type { ESTree } from "rolldown/utils";
3+
import { RESOLVED_RE as RAW_RE } from "./raw.ts";
4+
5+
// Bundlers parse the syntax but do not implement the semantics, so imports with a
6+
// `bytes` or `text` type attribute are rewritten to the internal prefixes of the raw plugin.
7+
// https://github.com/tc39/proposal-import-bytes
8+
// https://github.com/tc39/proposal-import-text
9+
10+
const TYPES = ["bytes", "text"] as const;
11+
type ImportType = (typeof TYPES)[number];
12+
13+
const ATTR_RE = /["']?type["']?\s*:\s*["'](bytes|text)["']/;
14+
const JS_ID_RE = /\.[cm]?[jt]sx?(\?.*)?$/;
15+
16+
// A module specifier with a `bytes` or `text` type attribute
17+
type TypedImport = {
18+
source: ESTree.StringLiteral;
19+
type: ImportType;
20+
// End of the syntax trailing the specifier (options argument or attributes clause)
21+
end: number;
22+
};
23+
24+
type Comment = { start: number; end: number };
25+
26+
export async function importAttributes(): Promise<Plugin> {
27+
const { RolldownMagicString } = await import("rolldown");
28+
const { parseSync } = await import("rolldown/utils");
29+
30+
return {
31+
name: "nitro:import-attributes",
32+
transform: {
33+
order: "pre",
34+
filter: {
35+
// Raw modules are file contents rather than source code. Their ids end with a `.js`
36+
// suffix, so without excluding them, files imported as text would be rewritten too.
37+
id: { include: JS_ID_RE, exclude: RAW_RE },
38+
code: ATTR_RE,
39+
},
40+
handler(code, id) {
41+
if (!JS_ID_RE.test(id) || RAW_RE.test(id) || !ATTR_RE.test(code)) {
42+
return; // In case the builder does not support filters
43+
}
44+
const filename = id.split("?")[0]!;
45+
const { program, comments, errors } = parseSync(filename, code);
46+
if (errors.length > 0) {
47+
this.warn(
48+
`Could not parse \`${filename}\` to transform \`bytes\` and \`text\` import attributes: ${errors[0]!.message}`
49+
);
50+
return;
51+
}
52+
53+
const imports = findTypedImports(program, code, comments);
54+
if (imports.length === 0) {
55+
return;
56+
}
57+
58+
const s = new RolldownMagicString(code);
59+
for (const { source, type, end } of imports) {
60+
s.update(source.start, source.end, JSON.stringify(`${type}:${source.value}`));
61+
s.remove(source.end, end);
62+
}
63+
64+
return {
65+
code: s.toString(),
66+
// `generateMap` returns a napi class whose fields are prototype getters, so spreading
67+
// or serializing it yields `{}`. Both builders accept a JSON source map string.
68+
map: s.generateMap({ hires: true, source: filename }).toString(),
69+
};
70+
},
71+
},
72+
};
73+
}
74+
75+
function findTypedImports(
76+
program: ESTree.Program,
77+
code: string,
78+
comments: Comment[]
79+
): TypedImport[] {
80+
const imports: TypedImport[] = [];
81+
walk(program, (node) => {
82+
switch (node.type) {
83+
// import("./file", { with: { type: "bytes" } })
84+
case "ImportExpression": {
85+
const options = node.options;
86+
if (!isStringLiteral(node.source) || options?.type !== "ObjectExpression") {
87+
return;
88+
}
89+
const type = optionsType(options);
90+
if (type) {
91+
imports.push({ source: node.source, type, end: options.end });
92+
}
93+
return;
94+
}
95+
// import x from "./file" with { type: "bytes" } (also `export ... from`)
96+
case "ImportDeclaration":
97+
case "ExportNamedDeclaration":
98+
case "ExportAllDeclaration": {
99+
const lastAttr = node.attributes.at(-1);
100+
const type = attributesType(node.attributes);
101+
if (!node.source || !lastAttr || !type) {
102+
return;
103+
}
104+
const end = clauseEnd(code, lastAttr.end, comments);
105+
if (end !== undefined) {
106+
imports.push({ source: node.source, type, end });
107+
}
108+
}
109+
}
110+
});
111+
return imports;
112+
}
113+
114+
// The `with { ... }` clause has no node of its own: its closing brace is the first
115+
// `}` following the last attribute that is not part of a comment.
116+
function clauseEnd(code: string, from: number, comments: Comment[]): number | undefined {
117+
for (let i = code.indexOf("}", from); i !== -1; i = code.indexOf("}", i + 1)) {
118+
if (!comments.some((comment) => i >= comment.start && i < comment.end)) {
119+
return i + 1;
120+
}
121+
}
122+
}
123+
124+
function attributesType(attributes: ESTree.ImportAttribute[]): ImportType | undefined {
125+
for (const attr of attributes) {
126+
const key = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
127+
if (key === "type" && isImportType(attr.value.value)) {
128+
return attr.value.value;
129+
}
130+
}
131+
}
132+
133+
function optionsType(options: ESTree.ObjectExpression): ImportType | undefined {
134+
const withOption = findProperty(options, "with");
135+
if (withOption?.type !== "ObjectExpression") {
136+
return;
137+
}
138+
const type = findProperty(withOption, "type");
139+
if (type && isStringLiteral(type) && isImportType(type.value)) {
140+
return type.value;
141+
}
142+
}
143+
144+
function findProperty(node: ESTree.ObjectExpression, name: string): ESTree.Expression | undefined {
145+
for (const prop of node.properties) {
146+
if (prop.type !== "Property" || prop.computed) {
147+
continue;
148+
}
149+
const key =
150+
prop.key.type === "Identifier"
151+
? prop.key.name
152+
: isStringLiteral(prop.key)
153+
? prop.key.value
154+
: undefined;
155+
if (key === name) {
156+
return prop.value;
157+
}
158+
}
159+
}
160+
161+
function isStringLiteral(node: ESTree.Node): node is ESTree.StringLiteral {
162+
return node.type === "Literal" && typeof (node as ESTree.StringLiteral).value === "string";
163+
}
164+
165+
function isImportType(value: string): value is ImportType {
166+
return TYPES.includes(value as ImportType);
167+
}
168+
169+
function walk(node: unknown, visit: (node: ESTree.Node) => void): void {
170+
if (Array.isArray(node)) {
171+
for (const child of node) {
172+
walk(child, visit);
173+
}
174+
return;
175+
}
176+
if (!node || typeof node !== "object") {
177+
return;
178+
}
179+
const record = node as Record<string, unknown>;
180+
if (typeof record.type === "string") {
181+
visit(node as ESTree.Node);
182+
}
183+
for (const key in record) {
184+
if (key !== "parent") {
185+
walk(record[key], visit);
186+
}
187+
}
188+
}

‎src/build/plugins/oxc.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { MinifyOptions } from "rolldown/experimental";
22
import type { OXCOptions } from "nitro/types";
33
import type { Plugin } from "rollup";
4+
import { RESOLVED_RE as rawModulesRE } from "./raw.ts";
45

56
export async function oxc(
67
options: OXCOptions & { sourcemap: boolean; minify: boolean | MinifyOptions }
@@ -10,7 +11,8 @@ export async function oxc(
1011
name: "nitro:oxc",
1112
transform: {
1213
filter: {
13-
id: /^(?!.*\/node_modules\/).*\.m?[jt]sx?$/,
14+
// Raw modules are already plain JS holding file contents; no need to transpile
15+
id: { include: /^(?!.*\/node_modules\/).*\.m?[jt]sx?$/, exclude: rawModulesRE },
1416
},
1517
handler(code, id) {
1618
const res = transformSync(id, code, {

0 commit comments

Comments
 (0)