feat: Add experimental vite plugin (#3184)

This PR adds a vite plugin for Fresh. This enables:

- HMR (only for islands for now)
- self-contained output bundles for both server and client
- smarter chunking

It uses vite's new Environment API under the hood.
This commit is contained in:
Marvin Hagemeister
2025-08-04 18:30:05 +02:00
committed by GitHub
parent 57596dc406
commit a1571b76ed
54 changed files with 2181 additions and 742 deletions
+128
View File
@@ -0,0 +1,128 @@
import type { Plugin } from "vite";
import {
type FreshViteConfig,
pathWithRoot,
type ResolvedFreshViteConfig,
} from "./utils.ts";
import { deno } from "./plugins/deno.ts";
import prefresh from "@prefresh/vite";
import { serverEntryPlugin } from "./plugins/server_entry.ts";
import { clientEntryPlugin } from "./plugins/client_entry.ts";
import { devServer } from "./plugins/dev_server.ts";
import { buildIdPlugin } from "./plugins/build_id.ts";
import { clientSnapshot } from "./plugins/client_snapshot.ts";
import { serverSnapshot } from "./plugins/server_snapshot.ts";
export function fresh(config?: FreshViteConfig): Plugin[] {
const fConfig: ResolvedFreshViteConfig = {
serverEntry: config?.serverEntry ?? "main.ts",
islandsDir: config?.islandsDir ?? "islands",
routeDir: config?.routeDir ?? "routes",
ignore: config?.ignore ?? [],
};
return [
{
name: "fresh",
config(config, env) {
return {
esbuild: {
jsx: "automatic",
jsxImportSource: "preact",
jsxDev: env.command === "serve",
},
resolve: {
alias: {
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat",
react: "preact/compat",
},
noExternal: true,
},
optimizeDeps: {
include: [
"preact",
"preact/compat",
"preact/debug",
"preact/devtools",
"preact/hooks",
"preact/jsx-runtime",
"preact/jsx-dev-runtime",
"@preact/signals",
],
},
publicDir: pathWithRoot("static", config.root),
builder: {
async buildApp(builder) {
// Build client env first
const clientEnv = builder.environments.client;
if (clientEnv !== undefined) {
await builder.build(clientEnv);
}
await Promise.all(
Object.values(builder.environments).filter((env) =>
env !== clientEnv
).map((env) => builder.build(env)),
);
},
},
environments: {
client: {
build: {
copyPublicDir: false,
manifest: true,
outDir: config.environments?.client?.build?.outDir ??
"_fresh/client",
rollupOptions: {
preserveEntrySignatures: "strict",
input: {
"client-entry": "fresh:client-entry",
"client-snapshot": "fresh:client-snapshot",
},
},
},
},
ssr: {
build: {
manifest: false,
copyPublicDir: false,
outDir: config.environments?.ssr?.build?.outDir ??
"_fresh/server",
rollupOptions: {
input: {
"server-entry": "fresh:server_entry",
},
},
},
},
},
};
},
configResolved(config) {
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, config.root);
fConfig.routeDir = pathWithRoot(fConfig.routeDir, config.root);
},
},
serverEntryPlugin(fConfig),
...serverSnapshot(fConfig),
clientEntryPlugin(),
clientSnapshot(fConfig),
buildIdPlugin(),
...devServer(),
prefresh({
include: [/\.[cm]?[tj]sx?$/],
exclude: [/node_modules/],
parserPlugins: [
"importMeta",
"explicitResourceManagement",
"topLevelAwait",
],
}),
deno(),
];
}
+51
View File
@@ -0,0 +1,51 @@
import type { Plugin } from "vite";
export function buildIdPlugin(): Plugin {
let buildId = "";
return {
name: "fresh:build-id",
async config(_, env) {
const isDev = env.command === "serve";
buildId = await getBuildId(isDev);
return {
define: {
BUILD_ID: JSON.stringify(buildId),
},
};
},
applyToEnvironment() {
return true;
},
resolveId(id) {
if (id === "fresh/build-id") {
return `\0fresh/build-id`;
}
},
load(id) {
if (id !== `\0fresh/build-id`) return;
return `export let BUILD_ID = ${JSON.stringify(buildId)};
export const DENO_DEPLOYMENT_ID = undefined;
export function setBuildId(id) {
BUILD_ID = id;
}`;
},
};
}
export async function getBuildId(dev: boolean): Promise<string> {
if (!dev) {
const bin = Deno.build.os === "windows" ? "git.exe" : "git";
const res = await new Deno.Command(bin, { args: ["rev-parse", "HEAD"] })
.output();
return new TextDecoder().decode(res.stdout);
}
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return String(arr[0]);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Plugin } from "vite";
export function clientEntryPlugin(): Plugin {
const modName = "fresh:client-entry";
return {
name: "fresh:client-entry",
applyToEnvironment(env) {
return env.name === "client";
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
load(id) {
if (id !== `\0${modName}`) return;
return `export * from "fresh/runtime-client";
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log("accepting")
});
import.meta.hot.on("fresh:reload", ev => {
console.log(ev)
window.location.reload();
});
}
`;
},
};
}
@@ -0,0 +1,79 @@
import type { Plugin, ViteDevServer } from "vite";
import type { ResolvedFreshViteConfig } from "../utils.ts";
import { crawlFsItem } from "fresh/internal-dev";
export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin {
const modName = "fresh:client-snapshot";
const islands = new Set<string>();
let server: ViteDevServer | undefined;
let isDev = false;
return {
name: "fresh:client-snapshot",
applyToEnvironment(env) {
return env.name === "client";
},
config(_, env) {
isDev = env.command === "serve";
return {
environments: {
client: {
build: {
rollupOptions: {
input: {
"client-snapshot": "fresh:client-snapshot",
},
},
},
},
},
};
},
async buildStart() {
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
for (let i = 0; i < result.islands.length; i++) {
const filePath = result.islands[i];
islands.add(filePath);
}
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
configureServer(devServer) {
server = devServer;
},
load(id) {
if (id !== `\0${modName}`) return;
const imports = Array.from(islands.keys()).map((file, i) => {
return `export const mod_${i} = await import(${JSON.stringify(file)});`;
}).join("\n");
if (isDev && server !== undefined) {
const mod = server.environments.ssr.moduleGraph.getModuleById(
"\0fresh:server-snapshot",
);
if (mod) {
server.environments.ssr.moduleGraph.invalidateModule(mod);
}
}
return `${imports}
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log("accepting client-snapshot")
});
}
`;
},
};
}
+187
View File
@@ -0,0 +1,187 @@
import type { Plugin } from "vite";
import {
type Loader,
RequestedModuleType,
ResolutionMode,
Workspace,
} from "@deno/loader";
import * as path from "@std/path";
interface DenoState {
type: RequestedModuleType;
}
export function deno(): Plugin {
let loader: Loader;
return {
name: "deno",
async configResolved() {
// TODO: Pass conditions
loader = await new Workspace({}).createLoader();
},
applyToEnvironment() {
return true;
},
async resolveId(id, importer, options) {
importer = isDenoSpecifier(importer)
? parseDenoSpecifier(importer).specifier
: importer;
try {
// Ensure we're passing a valid importer that Deno understands
const denoImporter = importer && !importer.startsWith("\0")
? importer
: undefined;
let resolved = await loader.resolve(
id,
denoImporter,
ResolutionMode.Import,
);
if (id === resolved) {
return id;
}
const type = getDenoType(options.attributes.type ?? "default");
if (
type !== RequestedModuleType.Default ||
/^(https?|jsr|npm):/.test(resolved) ||
// Vite does weird things to windows file paths
Deno.build.os === "windows"
) {
return toDenoSpecifier(resolved, type);
}
if (resolved.startsWith("file://")) {
resolved = path.fromFileUrl(resolved);
}
return {
id: resolved,
meta: {
deno: {
type,
},
},
};
} catch {
// ignore
}
},
async load(id) {
if (isDenoSpecifier(id)) {
const { type, specifier } = parseDenoSpecifier(id);
const result = await loader.load(specifier, type);
if (result.kind === "external") {
return null;
}
return {
code: new TextDecoder().decode(result.code),
};
}
if (id.startsWith("\0")) {
id = id.slice(1);
}
const meta = this.getModuleInfo(id)?.meta.deno as
| DenoState
| undefined
| null;
if (meta === null || meta === undefined) return;
const url = path.toFileUrl(id);
const result = await loader.load(url.href, meta.type);
if (result.kind === "external") {
return null;
}
return {
code: new TextDecoder().decode(result.code),
};
},
async transform(_, id, options) {
// This transform is a hack to be able to re-use Deno's precompile
// jsx transform.
if (!options?.ssr || !id.endsWith(".tsx") || id.endsWith(".jsx")) {
return;
}
let actualId = id;
if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id);
actualId = specifier;
}
if (path.isAbsolute(actualId)) {
actualId = path.toFileUrl(actualId).href;
}
const resolved = await loader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await loader.load(resolved, RequestedModuleType.Default);
if (result.kind === "external") {
return;
}
const code = new TextDecoder().decode(result.code);
return {
code,
};
},
};
}
export type DenoSpecifier = string & { __deno: string };
function isDenoSpecifier(str: unknown): str is DenoSpecifier {
return typeof str === "string" && str.startsWith("\0deno::");
}
function toDenoSpecifier(spec: string, type: RequestedModuleType) {
return `\0deno::${type}::${spec}`;
}
function parseDenoSpecifier(
spec: DenoSpecifier,
): { type: RequestedModuleType; specifier: string } {
const match = spec.match(/^\0deno::([^:]+)::(.*)$/)!;
let specifier = match[2];
const specMatch = specifier.match(/^(\w+):\/([^/].*)$/);
if (specMatch !== null) {
const protocol = specMatch[1];
let rest = specMatch[2];
if (protocol === "file") {
rest = "/" + rest;
}
specifier = `${protocol}://${rest}`;
}
return { type: +match[1], specifier };
}
function getDenoType(type: string): RequestedModuleType {
switch (type) {
case "json":
return RequestedModuleType.Json;
case "bytes":
return RequestedModuleType.Bytes;
case "text":
return RequestedModuleType.Text;
default:
return RequestedModuleType.Default;
}
}
+79
View File
@@ -0,0 +1,79 @@
import type { Plugin } from "vite";
import { nodeToRequest, responseToNode } from "../request.ts";
import * as path from "@std/path";
import { pathWithRoot } from "../utils.ts";
export function devServer(): Plugin[] {
let publicDir = "";
return [
{
name: "fresh:dev_server",
configResolved(cfg) {
publicDir = pathWithRoot(cfg.publicDir, cfg.root);
},
configureServer(server) {
const IGNORE_URLS = /^\/(@(vite|fs|id)|\.vite)\//;
server.middlewares.use(async (nodeReq, nodeRes, next) => {
const serverCfg = server.config.server;
const protocol = serverCfg.https ? "https" : "http";
const host = serverCfg.host ? serverCfg.host : "localhost";
const port = serverCfg.port;
const url = new URL(
`${protocol}://${host}:${port}${nodeReq.url ?? "/"}`,
);
// Check if it's a vite url
if (
IGNORE_URLS.test(url.pathname) ||
server.environments.client.moduleGraph.urlToModuleMap.has(
url.pathname,
)
) {
return next();
}
// Check if it's a static file first
// FIXME: Should this still go through fresh?
if (url.pathname !== "/") {
try {
await Deno.stat(path.join(publicDir, url.pathname));
return next();
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
return next(err);
}
}
}
const mod = await server.ssrLoadModule("fresh:server_entry");
try {
const req = nodeToRequest(nodeReq, url);
const res = await mod.default.fetch(req);
await responseToNode(res, nodeRes);
return nodeRes;
} catch (err) {
return next(err);
}
});
},
},
{
name: "fresh:server_hmr",
applyToEnvironment(env) {
return env.name === "ssr";
},
hotUpdate(options) {
const clientMod = options.server.environments.client.moduleGraph
.getModulesByFile(options.file);
if (clientMod === undefined) {
options.server.hot.send("fresh:reload");
}
},
},
];
}
+65
View File
@@ -0,0 +1,65 @@
import type { Plugin } from "vite";
import { generateServerEntry } from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
export function serverEntryPlugin(
options: ResolvedFreshViteConfig,
): Plugin {
const modName = "fresh:server_entry";
let serverEntry = "";
let serverOutDir = "";
let root = "";
let isDev = false;
return {
name: "fresh:server_entry",
applyToEnvironment(env) {
return env.name === "ssr";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
serverEntry = pathWithRoot(options.serverEntry, config.root);
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
config.root,
);
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
load(id) {
if (id !== `\0${modName}`) return;
let code = generateServerEntry({
root,
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
if (isDev) {
code += `if (import.meta.hot) import.meta.hot.accept();\n`;
}
return code;
},
async writeBundle() {
const outDir = path.dirname(serverOutDir);
await Deno.writeTextFile(
path.join(outDir, "server.js"),
`import server from "./server/server-entry.mjs";
export default {
fetch: server.fetch
};
`,
);
},
};
}
+189
View File
@@ -0,0 +1,189 @@
import type { Manifest, Plugin, ViteDevServer } from "vite";
import {
crawlFsItem,
fsAdapter,
generateSnapshotServer,
type IslandModChunk,
pathToSpec,
type PendingStaticFile,
specToName,
UniqueNamer,
} from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
import { getBuildId } from "./build_id.ts";
export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
const modName = "fresh:server-snapshot";
let isDev = false;
let server: ViteDevServer | undefined;
const namer = new UniqueNamer();
let clientOutDir = "";
let root = "";
let publicDir = "";
const islands = new Map<string, { name: string; chunk: string | null }>();
const islandSpecByName = new Map<string, string>();
return [{
name: "fresh:server-snapshot",
applyToEnvironment(env) {
return env.name === "ssr";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
publicDir = pathWithRoot(config.publicDir, config.root);
clientOutDir = pathWithRoot(
config.environments.client.build.outDir,
config.root,
);
},
configureServer(viteServer) {
server = viteServer;
},
async buildStart() {
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
async load(id) {
if (id !== `\0${modName}`) return;
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
for (let i = 0; i < result.islands.length; i++) {
const spec = result.islands[i];
const specName = specToName(spec);
const name = namer.getUniqueName(specName);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
}
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
}
islandMods = Array.from(islands.entries()).map(([id, def]) => {
return {
name: def.name,
server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
};
});
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
for (const chunk of Object.values(manifest)) {
if (chunk.name === "client-entry") {
clientEntry = pathToSpec(clientOutDir, chunk.file);
}
staticFiles.push({
filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null,
});
const namer = new UniqueNamer();
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
const serverPath = path.join(root, mod.src ?? id);
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: pathToSpec(clientOutDir, mod.file),
server: serverPath,
});
}
}
}
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({
filePath,
hash: null,
pathname: relative,
});
}
}
const code = await generateSnapshotServer({
outDir: root,
staticFiles,
buildId,
clientEntry,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
return path.toFileUrl(file).href;
},
});
return code;
},
}, {
name: "fresh:island-resolver",
resolveId(id) {
if (id.startsWith("fresh-island::")) {
const name = id.slice("fresh-island::".length);
const spec = islandSpecByName.get(name);
if (spec !== undefined) return spec;
}
},
}];
}
+84
View File
@@ -0,0 +1,84 @@
import type { IncomingMessage, ServerResponse } from "node:http";
export function nodeToRequest(node: IncomingMessage, url: URL): Request {
const controller = new AbortController();
node.once("aborted", () => controller.abort());
const body = undefined;
if (
node.method !== "HEAD" && node.method !== "GET" && node.method !== "OPTIONS"
) {
// FIXME
}
return new Request(url, {
headers: node.headers as Record<string, string>,
method: node.method,
body,
signal: controller.signal,
});
}
export async function responseToNode(
res: Response,
node: ServerResponse<IncomingMessage>,
): Promise<void> {
res.headers.forEach((value, key) => {
node.setHeader(key, value);
});
node.writeHead(res.status);
if (res.body === null) {
node.end();
return;
}
if (res.body.locked) {
node.end(`Error: Response body is locked.`);
return;
}
const reader = res.body.getReader();
if (node.destroyed) {
await reader.cancel();
return;
}
const cancel = (error: unknown) => {
node.off("close", cancel);
node.off("error", cancel);
// Can't respond anymore with error
reader.cancel(error).catch(() => {});
if (error) {
node.destroy(error instanceof Error ? error : new Error(String(error)));
}
};
node.on("close", cancel);
node.on("error", cancel);
async function next() {
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!node.write(value)) {
node.once("drain", next);
return;
}
}
node.end();
} catch (error) {
cancel(error);
}
}
next();
}
+41
View File
@@ -0,0 +1,41 @@
import * as path from "@std/path";
import type { FsRouteFileNoMod, UniqueNamer } from "fresh/internal-dev";
export function pathWithRoot(fileOrDir: string, root?: string): string {
if (path.isAbsolute(fileOrDir)) return fileOrDir;
if (root === undefined) {
return path.join(Deno.cwd(), fileOrDir);
}
if (path.isAbsolute(root)) return path.join(root, fileOrDir);
return path.join(Deno.cwd(), root, fileOrDir);
}
export interface FreshState {
namer: UniqueNamer;
root: string;
serverEntry: string;
islandDir: string;
routeDir: string;
dev: boolean;
islands: Map<string, { name: string; chunk: string | null }>;
// deno-lint-ignore no-explicit-any
routes: FsRouteFileNoMod<any>[];
clientOutDir: string;
serverOutDir: string;
}
export interface ClientSnapshot {
entry: string;
}
export interface FreshViteConfig {
serverEntry?: string;
islandsDir?: string;
routeDir?: string;
ignore?: RegExp[];
}
export type ResolvedFreshViteConfig = Required<FreshViteConfig>;