Repository navigation
Expand file tree
/
Copy pathbuild.config.ts
More file actions
248 lines (235 loc) · 8.05 KB
/
Copy pathbuild.config.ts
File metadata and controls
248 lines (235 loc) · 8.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import { defineBuildConfig } from "obuild/config";
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import type { CodeSplittingOptions } from "rolldown";
import { glob } from "tinyglobby";
const isStub = process.argv.includes("--stub");
// Optional dependencies imported on demand from the user project (see `src/utils/dep.ts`)
const optionalDeps = [
"@vercel/queue",
"dotenv",
"giget",
"jiti",
"rolldown",
"rollup",
"vite",
"xml2js",
"zephyr-agent",
];
// Optional dependencies of bundled libraries, replaced by an on demand import (see `src/shims/`)
const shimmedDeps = ["dotenv", "giget", "jiti"];
// Optional dependencies imported by the public types, with a fallback type when not installed
// (see `OptionalDepType` in `src/types/_utils.ts`)
const optionalTypeDeps = [
"@cloudflare/workers-types",
"@vercel/queue",
"cloudflare:workers",
"rolldown",
"rollup",
];
const pkg = await import("./package.json", { with: { type: "json" } }).then((r) => r.default || r);
export default defineBuildConfig({
entries: [
{
type: "bundle",
input: ["src/builder.ts", "src/cli/index.ts", "src/types/index.ts", "src/vite.ts"],
minifyLibs: true,
license: { gzip: true },
},
{
// Every runtime file stays an entry (build code references them by path). Bundling them
// together inlines dependencies into chunks shared across all runtime entries.
// Kept separate from the main bundle so runtime chunks never pull in build-time code.
type: "bundle",
input: await glob(["src/runtime/**/*.ts", "src/presets/*/runtime/**/*.ts"]),
minifyLibs: true,
dts: { entry: "src/runtime/**/*.ts", generator: "oxc" },
rolldown: {
// Keep side-effect imports of virtual modules (e.g. `import "#nitro/virtual/polyfills"`)
treeshake: {
moduleSideEffects: (id, external) => (external ? id.startsWith("#") : undefined),
},
plugins: [
{
name: "nitro:runtime-chunks",
outputOptions: (o) => ({
...o,
chunkFileNames: (chunk) =>
libChunkFileName(chunk, "runtime/_libs") || "runtime/_chunks/[name].mjs",
}),
// Polyfills are always imported first in source, but rolldown hoists chunk and other
// external imports above them. Move them back so they still evaluate first.
renderChunk(code) {
const polyfillsImport = `import "#nitro/virtual/polyfills";\n`;
if (code.includes(polyfillsImport)) {
return polyfillsImport + code.replace(polyfillsImport, "");
}
},
},
],
},
},
{
// Plain JS runtime files loaded as-is (dev worker and entries)
type: "transform",
input: "src/runtime/",
outDir: "dist/runtime",
filter: (id) => id.endsWith(".mjs"),
},
{
type: "transform",
input: "src/presets/",
outDir: "dist/presets",
filter: (id) => id.includes("runtime/") && id.endsWith(".mjs"),
dts: false,
},
],
hooks: {
rolldownConfig(config) {
config.platform = "node";
config.resolve ??= {};
config.resolve.alias ??= {};
Object.assign(
config.resolve.alias,
{
"node-fetch-native/proxy": "node-fetch-native/native",
"node-fetch-native": "node-fetch-native/native",
},
Object.fromEntries(
shimmedDeps.map((dep) => [
dep,
fileURLToPath(new URL(`src/shims/${dep}.ts`, import.meta.url)),
])
)
);
config.external ??= [];
(config.external as (string | RegExp)[]).push(
"nitro",
...Object.keys(pkg.exports || {}).map((key) => key.replace(/^./, "nitro")),
...Object.keys(pkg.dependencies),
...optionalDeps.filter((dep) => !shimmedDeps.includes(dep)),
"typescript",
"firebase-functions",
"@scalar/api-reference",
"cloudflare:workers",
"@cloudflare/workers-types",
// unplugin deps
"@rspack/core",
"@farmfe/core",
"webpack",
"unloader",
// CommonJS `.d.ts` modules that rolldown-plugin-dts cannot bundle
"webpack-virtual-modules",
/^zod(\/|$)/
);
},
rolldownOutput(config) {
(config.codeSplitting as CodeSplittingOptions).groups?.unshift(
{
test: /src[/\\]build[/\\](plugins|virtual|\w+\.ts)/,
name: "_build/common",
},
{ test: /src[/\\](utils)[/\\]/, name: "_chunks/utils" }
);
config.chunkFileNames = (chunk) => {
if (chunk.name.startsWith("_")) {
return `[name].mjs`;
}
if (chunk.name === "rolldown-runtime") {
return `_common.mjs`;
}
const libChunk = libChunkFileName(chunk, "_libs");
if (libChunk) {
return libChunk;
}
if (chunk.moduleIds.every((id) => /src[/\\]cli[/\\]/.test(id))) {
return `cli/_chunks/[name].mjs`;
}
if (chunk.moduleIds.every((id) => /build[/\\]vite[/\\]/.test(id))) {
return `_build/vite.[name].mjs`;
}
if (chunk.moduleIds.every((id) => /build[/\\]rolldown[/\\]/.test(id))) {
return `_build/rolldown.mjs`;
}
if (chunk.moduleIds.every((id) => /build[/\\]rollup[/\\]|build[/\\]plugins/.test(id))) {
return `_build/rollup.mjs`;
}
if (chunk.moduleIds.every((id) => /src[/\\]dev[/\\]|src[/\\]runtime/.test(id))) {
return `_dev.mjs`;
}
if (chunk.moduleIds.every((id) => /src[/\\]presets/.test(id))) {
return `_presets.mjs`;
}
if (
chunk.moduleIds.every((id) => /src[/\\]build[/\\]|src[/\\]presets|src[/\\]utils/.test(id))
) {
return `_build/shared.mjs`;
}
if (chunk.moduleIds.every((id) => /src[/\\](runner|dev|runtime)/.test(id))) {
return `_chunks/dev.mjs`;
}
return "_chunks/nitro.mjs";
};
},
async end() {
if (isStub) {
return;
}
// Bundle docs
const { exportSource } = await import("mdzilla");
await exportSource("./docs", "./dist/docs", {
title: "Nitro Documentation",
filter: (e: { entry: { path: string } }) => !e.entry.path.startsWith("/blog"),
});
// Optional dependency types
for (const file of await glob("dist/**/*.d.mts")) {
const code = await readFile(file, "utf8");
const lines = code.split("\n").flatMap((line) => {
if (
!optionalTypeDeps.some(
(dep) => line.includes(`from "${dep}"`) || line.includes(`import("${dep}")`)
)
) {
return [line];
}
if (!/^import (?:type )?\{[^}]+\} from "[^"]+";$/.test(line)) {
throw new Error(`Unexpected optional dependency type import in \`${file}\`: ${line}`);
}
return ["// @ts-ignore optional dependency", line];
});
if (lines.join("\n") !== code) {
await writeFile(file, lines.join("\n"));
}
}
// Vite types
await writeFile(
"dist/vite.d.mts",
`import "vite/client";\nimport "nitro/vite/types";\n${await readFile("dist/vite.d.mts", "utf8")}`
);
},
},
});
function libChunkFileName(chunk: { moduleIds: string[] }, dir: string): string | undefined {
const pkgRe = /.*[/\\](?:node_modules|shims)[/\\](?<package>@[^/\\]+[/\\][^/\\]+|[^/\\]+)/;
if (!chunk.moduleIds.every((id) => pkgRe.test(id))) {
return;
}
const pkgNames = [
...new Set(
chunk.moduleIds
.map((id) => id.match(pkgRe)?.groups?.package)
.filter(Boolean)
.map((name) => name!.split(/[/\\]/).pop()!)
.filter(Boolean)
),
].sort((a, b) => a.length - b.length);
let chunkName = "";
for (const name of pkgNames) {
const separator = chunkName ? "+" : "";
if ((chunkName + separator + name).length > 30) {
break;
}
chunkName += separator + name;
}
return `${dir}/${chunkName || "_"}.mjs`;
}