-
-
Notifications
You must be signed in to change notification settings - Fork 886
Expand file tree
/
Copy pathenv.ts
More file actions
250 lines (238 loc) · 8.94 KB
/
Copy pathenv.ts
File metadata and controls
250 lines (238 loc) · 8.94 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
249
250
import type { EnvironmentOptions, RollupCommonJSOptions, Plugin as VitePlugin } from "vite";
import type { NitroPluginContext, ServiceConfig } from "./types.ts";
import type { RunnerName } from "env-runner";
import { RunnerManager, loadRunner } from "env-runner";
import { join, resolve } from "node:path";
import { runtimeDependencies, runtimeDir } from "nitro/meta";
import { resolveModulePath } from "exsolve";
import { isAbsolute } from "pathe";
export function createNitroEnvironment(ctx: NitroPluginContext): EnvironmentOptions {
const isWorkerdRunner = _isWorkerdRunner(ctx);
return {
consumer: "server",
build: {
rollupOptions: ctx.bundlerConfig!.rollupConfig as any,
rolldownOptions: ctx.bundlerConfig!.rolldownConfig as any,
minify: ctx.nitro!.options.minify,
emptyOutDir: false,
sourcemap: ctx.nitro!.options.sourcemap,
commonjsOptions: ctx.nitro!.options.commonJS as RollupCommonJSOptions,
copyPublicDir: false,
},
resolve: {
noExternal: ctx.nitro!.options.dev
? isWorkerdRunner
? true
: [
/^nitro(\/|$)/,
new RegExp(`^(${runtimeDependencies.join("|")})$`), // virtual resolutions in vite skip plugin hooks
...ctx.bundlerConfig!.base.noExternal,
]
: true, // production build is standalone
// workerd cannot handle CJS modules, so we must avoid the "node" export
// condition which often resolves to CJS entries.
conditions: isWorkerdRunner
? ["workerd", "worker", ...ctx.nitro!.options.exportConditions!.filter((c) => c !== "node")]
: _resolveConditions(ctx),
externalConditions: _resolveConditions(ctx).filter((c) => !/browser|wasm|module/.test(c)),
},
define: {
// Workaround for tanstack-start (devtools)
"process.env.NODE_ENV": JSON.stringify(ctx.nitro!.options.dev ? "development" : "production"),
},
dev: {
createEnvironment: async (envName, envConfig) => {
const entry = resolve(runtimeDir, "internal/vite/dev-entry.mjs");
const { createFetchableDevEnvironment } = await import("./dev.ts");
const env = createFetchableDevEnvironment(envName, envConfig, getEnvRunner(ctx), entry, {
preventExternalize: isWorkerdRunner,
});
ctx._transformRequest = (id) => env.transformRequest(id);
(ctx._viteEnvs ??= new Map()).set(envName, entry);
return env;
},
},
};
}
export function createServiceEnvironment(
ctx: NitroPluginContext,
name: string,
serviceConfig: ServiceConfig
): EnvironmentOptions {
const isDev = ctx.nitro!.options.dev;
const isWorkerdRunner = _isWorkerdRunner(ctx);
// Keep SSR-emitted asset URLs (e.g. CSS `<link>` tags) aligned with the
// relocated client assets, so both resolve to the same content-addressed file.
// Both the directory (`assetsDir`) and the content-hash length must match the
// client environment, otherwise the SSR bundle references e.g.
// `app-<hash:8>.css` while the client emits `app-<hash:16>.css` → 404.
const buildAssetsDir = ctx.nitro!.options.buildAssetsDir;
return {
consumer: "server",
build: {
rollupOptions: {
input: { index: serviceConfig.entry },
...(isDev ? {} : { external: [/^nitro(\/|$)/] }),
output: {
minifyInternalExports: false,
// Must match the client environment's `[hash:16]` asset pattern (see
// `useLongerAssetHashes` in `plugin.ts`) so a `?url` asset import
// resolves to the same filename on both sides.
...(buildAssetsDir
? { assetFileNames: `${buildAssetsDir}/[name]-[hash:16][extname]` }
: {}),
},
},
minify: ctx.nitro!.options.minify,
sourcemap: ctx.nitro!.options.sourcemap,
outDir: join(ctx.nitro!.options.buildDir, "vite/services", name),
emptyOutDir: true,
copyPublicDir: false,
...(buildAssetsDir ? { assetsDir: buildAssetsDir } : {}),
},
resolve: {
...(isDev ? { noExternal: isWorkerdRunner ? true : [/^nitro(\/|$)/] } : {}),
conditions: isWorkerdRunner
? ["workerd", "worker", ...ctx.nitro!.options.exportConditions!.filter((c) => c !== "node")]
: _resolveConditions(ctx),
externalConditions: _resolveConditions(ctx).filter((c) => !/browser|wasm|module/.test(c)),
},
dev: {
createEnvironment: async (envName, envConfig) => {
const entry = tryResolve(serviceConfig.entry);
(ctx._viteEnvs ??= new Map()).set(envName, entry);
const { createFetchableDevEnvironment } = await import("./dev.ts");
return createFetchableDevEnvironment(envName, envConfig, getEnvRunner(ctx), entry, {
preventExternalize: isWorkerdRunner,
});
},
},
};
}
export function createServiceEnvironments(
ctx: NitroPluginContext
): Record<string, EnvironmentOptions> {
return Object.fromEntries(
Object.entries(ctx.services).map(([name, config]) => [
name,
createServiceEnvironment(ctx, name, config),
])
);
}
export async function initEnvRunner(ctx: NitroPluginContext) {
if (ctx._envRunner) {
return ctx._envRunner;
}
if (!ctx._initPromise) {
ctx._initPromise = (async () => {
const manager = new RunnerManager();
let _retries = 0;
manager.onClose((_runner, cause) => {
if (_retries++ < 3) {
ctx.nitro!.logger.info("Restarting env runner...", cause ? `Cause: ${cause}` : "");
_loadRunner(ctx, manager);
} else {
ctx.nitro!.logger.error(
"Env runner failed after 3 retries.",
cause ? `Last cause: ${cause}` : ""
);
}
});
manager.onReady(() => {
_retries = 0;
if (ctx._viteEnvs) {
for (const [name, entry] of ctx._viteEnvs) {
manager.sendMessage({
type: "custom",
event: "nitro:vite-env",
data: { name, entry },
});
}
}
});
await _loadRunner(ctx, manager);
ctx._envRunner = manager;
return manager;
})();
}
return await ctx._initPromise;
}
export function getEnvRunner(ctx: NitroPluginContext) {
if (!ctx._envRunner) {
throw new Error("Env runner not initialized. Call initEnvRunner() first.");
}
return ctx._envRunner;
}
export async function reloadEnvRunner(ctx: NitroPluginContext) {
const manager = ctx._envRunner;
if (!manager) {
return initEnvRunner(ctx);
}
await _loadRunner(ctx, manager);
return manager;
}
async function _loadRunner(ctx: NitroPluginContext, manager: RunnerManager) {
const runnerName = _devRunner(ctx);
const entry = resolve(runtimeDir, "internal/vite/dev-worker.mjs");
let runner;
if (runnerName === "miniflare") {
const { MiniflareEnvRunner } = await import("env-runner/runners/miniflare");
runner = new MiniflareEnvRunner({
name: "nitro-vite",
wrangler: {
...ctx.nitro!.options.cloudflare?.wrangler,
},
wranglerEnv: ctx.nitro!.options.cloudflare?.wranglerEnv,
data: { entry },
});
} else {
runner = await loadRunner(runnerName, {
name: "nitro-vite",
data: { entry },
});
}
await manager.reload(runner);
}
// Resolve export conditions for the (non-workerd) environment.
// In dev with the default `node-worker` runner, the module runner executes in a
// worker thread of the same host runtime (Bun => Bun, Deno => Deno), so prepend
// the matching export condition to let packages resolve their runtime-native
// entry instead of the `node` one. Other runners (process-based or miniflare)
// run in a different runtime, so the host condition must not leak into their
// resolution; outside of dev the conditions are returned unchanged.
function _resolveConditions(ctx: NitroPluginContext): string[] {
const exportConditions = ctx.nitro!.options.exportConditions!;
if (!ctx.nitro!.options.dev || _devRunner(ctx) !== "node-worker") {
return exportConditions;
}
const runtimeCondition =
typeof (globalThis as any).Bun !== "undefined"
? "bun"
: typeof (globalThis as any).Deno !== "undefined"
? "deno"
: undefined;
return runtimeCondition && !exportConditions.includes(runtimeCondition)
? [runtimeCondition, ...exportConditions]
: exportConditions;
}
function _devRunner(ctx: NitroPluginContext): RunnerName {
return (ctx.nitro!.options.devServer.runner ||
process.env.NITRO_DEV_RUNNER ||
"node-worker") as RunnerName;
}
// workerd-based runners (miniflare) cannot handle CJS externals via import(),
// so all dependencies must be processed through Vite's transform pipeline.
function _isWorkerdRunner(ctx: NitroPluginContext): boolean {
return _devRunner(ctx) === "miniflare";
}
function tryResolve(id: string) {
if (/^[~#/\0]/.test(id) || isAbsolute(id)) {
return id;
}
const resolved = resolveModulePath(id, {
suffixes: ["", "/index"],
extensions: ["", ".ts", ".mjs", ".cjs", ".js", ".mts", ".cts"],
try: true,
});
return resolved || id;
}