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:
+175
-120
@@ -1,11 +1,10 @@
|
||||
import {
|
||||
type BuildCache,
|
||||
type FileSnapshot,
|
||||
IslandPreparer,
|
||||
type StaticFile,
|
||||
} from "../build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
import { SEPARATOR as WINDOWS_SEPARATOR } from "@std/path/windows/constants";
|
||||
import * as pathWin32 from "@std/path/windows";
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import type { FileTransformer } from "./file_transformer.ts";
|
||||
@@ -16,6 +15,8 @@ import type { Command } from "../commands.ts";
|
||||
import type { ServerIslandRegistry } from "../context.ts";
|
||||
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
||||
|
||||
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
|
||||
|
||||
export interface MemoryFile {
|
||||
hash: string | null;
|
||||
contentType: string;
|
||||
@@ -60,16 +61,24 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
|
||||
#commands: Command<State>[] = [];
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string;
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
|
||||
this.#config = config;
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.root = config.root;
|
||||
|
||||
this.clientEntry = getClientEntry(config.buildId);
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
@@ -220,12 +229,17 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
||||
#fsRoutes: FsRoute<State>;
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string = "";
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.#config = config;
|
||||
@@ -308,155 +322,62 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles = new Map<string, FileSnapshot>();
|
||||
const staticFiles: PendingStaticFile[] = [];
|
||||
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
|
||||
const file = await Deno.open(filePath);
|
||||
const hash = await hashContent(file.readable);
|
||||
|
||||
staticFiles.set(name, {
|
||||
name,
|
||||
hash,
|
||||
filePath: path.relative(root, filePath),
|
||||
contentType: getContentType(filePath),
|
||||
});
|
||||
staticFiles.push({ filePath, pathname: name, hash: null });
|
||||
}
|
||||
|
||||
for (const [name, maybeHash] of this.#processedFiles.entries()) {
|
||||
let hash = maybeHash;
|
||||
|
||||
// Ignore esbuild meta file. It's not intended for serving
|
||||
if (name === "/metafile.json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = path.join(outDir, "static", name);
|
||||
if (maybeHash === null) {
|
||||
const file = await Deno.open(filePath);
|
||||
hash = await hashContent(file.readable);
|
||||
}
|
||||
|
||||
staticFiles.set(name, {
|
||||
name,
|
||||
hash,
|
||||
filePath: path.relative(root, filePath),
|
||||
contentType: getContentType(filePath),
|
||||
});
|
||||
staticFiles.push({ filePath, pathname: name, hash: maybeHash });
|
||||
}
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "static-files.json"),
|
||||
JSON.stringify(Array.from(staticFiles.values()), null, 2),
|
||||
);
|
||||
|
||||
const islandSpecifiers: string[] = [];
|
||||
for (const spec of this.islandModNameToChunk.keys()) {
|
||||
islandSpecifiers.push(spec);
|
||||
}
|
||||
|
||||
const editWarning =
|
||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||
|
||||
const islands = Array.from(this.islandModNameToChunk.values());
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "snapshot.js"),
|
||||
`${editWarning}
|
||||
|
||||
import { IslandPreparer } from "fresh/do-not-use";
|
||||
import staticFileData from "./static-files.json" with { type: "json" };
|
||||
|
||||
// Import islands
|
||||
${
|
||||
islands
|
||||
.map((item) => {
|
||||
const spec = pathToSpec(outDir, item.server);
|
||||
return `import * as ${item.name} from "${spec}";`;
|
||||
})
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
// Import routes
|
||||
${
|
||||
this.#fsRoutes.files
|
||||
.map((item, i) => {
|
||||
if (item.lazy) return null;
|
||||
const spec = pathToSpec(outDir, item.filePath);
|
||||
return `import * as fsRoute_${i} from "${spec}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
export const version = ${JSON.stringify(this.#config.buildId)};
|
||||
|
||||
const prefix = \`/_fresh/js/\${version}\`;
|
||||
|
||||
export const islands = new Map();
|
||||
const islandPreparer = new IslandPreparer();
|
||||
${
|
||||
islands.map((item) => {
|
||||
// Strip prefix
|
||||
const prefix = `/_fresh/js/${this.#config.buildId}`;
|
||||
const chunkName = item.browser
|
||||
? item.browser.slice(prefix.length)
|
||||
: item.browser;
|
||||
return `islandPreparer.prepare(islands, ${item.name}, \`\${prefix}${chunkName}\`, ${
|
||||
JSON.stringify(item.name)
|
||||
});`;
|
||||
}).join("\n")
|
||||
}
|
||||
|
||||
export const staticFiles = new Map();
|
||||
for (let i = 0; i < staticFileData.length; i++) {
|
||||
const data = staticFileData[i];
|
||||
staticFiles.set(data.name, data);
|
||||
}
|
||||
|
||||
export const fsRoutes = [
|
||||
${
|
||||
this.#fsRoutes.files
|
||||
.map((item, i) => {
|
||||
const id = JSON.stringify(item.id);
|
||||
const pattern = JSON.stringify(item.pattern);
|
||||
const type = JSON.stringify(item.type);
|
||||
const routePattern = JSON.stringify(item.routePattern);
|
||||
|
||||
let mod = "";
|
||||
if (item.lazy) {
|
||||
const spec = pathToSpec(outDir, item.filePath);
|
||||
mod = `() => import(${JSON.stringify(spec)})`;
|
||||
} else {
|
||||
mod = `fsRoute_${i}`;
|
||||
}
|
||||
|
||||
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
|
||||
})
|
||||
.join("\n")
|
||||
}
|
||||
];
|
||||
`,
|
||||
await generateSnapshotServer({
|
||||
buildId: this.#config.buildId,
|
||||
clientEntry: getClientEntry(this.#config.buildId),
|
||||
staticFiles,
|
||||
islands,
|
||||
writeSpecifier: (filePath) => {
|
||||
return pathToSpec(outDir, filePath);
|
||||
},
|
||||
fsRoutesFiles: this.#fsRoutes.files,
|
||||
outDir: root,
|
||||
}),
|
||||
);
|
||||
|
||||
// TODO: Make main file configurable
|
||||
const appPath = path.relative(outDir, root);
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "server.js"),
|
||||
`${editWarning}
|
||||
import { setBuildCache, ProdBuildCache, path } from "fresh/do-not-use";
|
||||
import * as snapshot from "./snapshot.js";
|
||||
import { app } from "${appPath}/main.ts";
|
||||
|
||||
const root = path.join(import.meta.dirname, ${JSON.stringify(appPath)});
|
||||
setBuildCache(app, new ProdBuildCache(root, snapshot));
|
||||
|
||||
export default {
|
||||
fetch: app.handler()
|
||||
}`,
|
||||
generateServerEntry({
|
||||
root: appPath,
|
||||
serverEntry: path
|
||||
.join(appPath, "main.ts")
|
||||
.replaceAll(/[\\/]+/g, "/"),
|
||||
snapshotSpecifier: "./snapshot.js",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function hashContent(
|
||||
const EDIT_WARNING =
|
||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||
|
||||
export async function hashContent(
|
||||
content: Uint8Array | ReadableStream<Uint8Array>,
|
||||
): Promise<string> {
|
||||
const buffer = await new Response(content).arrayBuffer();
|
||||
@@ -476,3 +397,137 @@ export function getContentType(filePath: string): string {
|
||||
function maybeToFileUrl(file: string) {
|
||||
return file.startsWith("file://") ? file : path.toFileUrl(file).href;
|
||||
}
|
||||
|
||||
export interface PendingStaticFile {
|
||||
pathname: string;
|
||||
filePath: string;
|
||||
hash: string | null;
|
||||
}
|
||||
|
||||
export async function generateSnapshotServer(
|
||||
options: {
|
||||
outDir: string;
|
||||
buildId: string;
|
||||
clientEntry: string;
|
||||
islands: IslandModChunk[];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
fsRoutesFiles: FsRouteFileNoMod<any>[];
|
||||
staticFiles: PendingStaticFile[];
|
||||
writeSpecifier: (filePath: string) => string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const {
|
||||
islands,
|
||||
writeSpecifier,
|
||||
fsRoutesFiles,
|
||||
outDir,
|
||||
} = options;
|
||||
|
||||
const islandImports = islands
|
||||
.map((item) => {
|
||||
const spec = writeSpecifier(item.server);
|
||||
return `import * as ${item.name} from "${spec}";`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const fsRouteImports = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
if (item.lazy) return null;
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
return `import * as fsRoute_${i} from "${spec}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
const islandMarkers = islands.map((item) => {
|
||||
const browser = JSON.stringify(item.browser);
|
||||
const name = JSON.stringify(item.name);
|
||||
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name});`;
|
||||
}).join("\n");
|
||||
|
||||
const serializedFsRoutes = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
const id = JSON.stringify(item.id);
|
||||
const pattern = JSON.stringify(item.pattern);
|
||||
const type = JSON.stringify(item.type);
|
||||
const routePattern = JSON.stringify(item.routePattern);
|
||||
|
||||
let mod = "";
|
||||
if (item.lazy) {
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
mod = `() => import(${JSON.stringify(spec)})`;
|
||||
} else {
|
||||
mod = `fsRoute_${i}`;
|
||||
}
|
||||
|
||||
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const staticFiles = await Promise.all(
|
||||
options.staticFiles.map(async (item) => {
|
||||
const file = await Deno.open(item.filePath);
|
||||
const hash = item.hash ? item.hash : await hashContent(file.readable);
|
||||
const url = new URL(item.pathname, "http://localhost");
|
||||
|
||||
return {
|
||||
name: url.pathname,
|
||||
hash,
|
||||
filePath: path.isAbsolute(item.filePath)
|
||||
? path.relative(outDir, item.filePath)
|
||||
: item.filePath,
|
||||
contentType: getContentType(item.filePath),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return `${EDIT_WARNING}
|
||||
import { IslandPreparer } from "fresh/internal";
|
||||
${islandImports}
|
||||
${fsRouteImports}
|
||||
|
||||
export const clientEntry = ${JSON.stringify(options.clientEntry)}
|
||||
export const version = ${JSON.stringify(options.buildId)}
|
||||
|
||||
export const islands = new Map();
|
||||
const islandPreparer = new IslandPreparer();
|
||||
${islandMarkers}
|
||||
|
||||
export const staticFiles = new Map([
|
||||
${
|
||||
staticFiles.map((def) =>
|
||||
` [${JSON.stringify(def.name)}, ${JSON.stringify(def)}]`
|
||||
).join(",\n")
|
||||
}
|
||||
]);
|
||||
|
||||
export const fsRoutes = [
|
||||
${serializedFsRoutes}
|
||||
];
|
||||
`.replaceAll(/\n[\n]+/g, "\n\n");
|
||||
}
|
||||
|
||||
export function generateServerEntry(
|
||||
options: {
|
||||
root: string;
|
||||
serverEntry: string;
|
||||
snapshotSpecifier: string;
|
||||
},
|
||||
): string {
|
||||
return `${EDIT_WARNING}
|
||||
import { setBuildCache, ProdBuildCache, path } from "fresh/internal";
|
||||
import * as snapshot from "${options.snapshotSpecifier}";
|
||||
import { app } from "${options.serverEntry}";
|
||||
|
||||
const root = "";
|
||||
setBuildCache(app, new ProdBuildCache(root, snapshot), "production");
|
||||
|
||||
export default {
|
||||
fetch: app.handler()
|
||||
};
|
||||
`;
|
||||
}
|
||||
|
||||
function getClientEntry(buildId: string) {
|
||||
return `/_fresh/js/${buildId}/fresh-runtime.js`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user