Skip to content

Commit

Permalink
some refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Nov 9, 2023
1 parent 62b829e commit b7a425f
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 46 deletions.
6 changes: 3 additions & 3 deletions packages/waku/src/lib/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,15 +254,15 @@ const emitRscFiles = async (
if (!rscFileSet.has(destFile)) {
rscFileSet.add(destFile);
fs.mkdirSync(path.dirname(destFile), { recursive: true });
const [pipeable] = await renderRSC({
const [readable] = await renderRSC({
input,
method: "GET",
headers: {},
command: "build",
context,
moduleIdCallback: (id) => addClientModule(input, id),
});
await pipeline(pipeable, fs.createWriteStream(destFile));
await pipeline(readable, fs.createWriteStream(destFile));
}
}
}),
Expand All @@ -288,7 +288,7 @@ const emitHtmlFiles = async (
});
const htmlFiles = await Promise.all(
Object.entries(buildConfig).map(
async ([pathStr, { entries, context, customCode }]) => {
async ([pathStr, { entries, customCode, context }]) => {
const destFile = path.join(
config.rootDir,
config.distDir,
Expand Down
77 changes: 36 additions & 41 deletions packages/waku/src/lib/middleware/rsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,24 @@ type Middleware = (

export function rsc<Context>(options: {
command: "dev" | "start";
ssr: boolean;
ssr?: boolean;
unstable_prehook?: (req: IncomingMessage, res: ServerResponse) => Context;
unstable_posthook?: (
req: IncomingMessage,
res: ServerResponse,
ctx: Context,
) => void;
}): Middleware {
if (!options.unstable_prehook && options.unstable_posthook) {
const { command, ssr, unstable_prehook, unstable_posthook } = options;
if (!unstable_prehook && unstable_posthook) {
throw new Error("prehook is required if posthook is provided");
}
const configPromise = resolveConfig();

let viteServer: ViteDevServer | undefined;
let lastViteServer: ViteDevServer | undefined;
const getViteServer = async (): Promise<ViteDevServer> => {
if (viteServer) {
return viteServer;
if (lastViteServer) {
return lastViteServer;
}
const config = await configPromise;
const { createServer: viteCreateServer } = await import("vite");
Expand All @@ -48,7 +49,7 @@ export function rsc<Context>(options: {
const { rscHmrPlugin, hotImport } = await import(
"../vite-plugin/rsc-hmr-plugin.js"
);
viteServer = await viteCreateServer({
const viteServer = await viteCreateServer({
root: path.join(config.rootDir, config.srcDir),
optimizeDeps: {
include: ["react-server-dom-webpack/client"],
Expand All @@ -63,9 +64,9 @@ export function rsc<Context>(options: {
],
server: { middlewareMode: true },
});
const vite = viteServer;
registerReloadCallback((type) => vite.ws.send({ type }));
registerImportCallback((source) => hotImport(vite, source));
registerReloadCallback((type) => viteServer.ws.send({ type }));
registerImportCallback((source) => hotImport(viteServer, source));
lastViteServer = viteServer;
return viteServer;
};

Expand All @@ -75,7 +76,7 @@ export function rsc<Context>(options: {
if (!publicIndexHtml) {
const publicIndexHtmlFile = path.join(
config.rootDir,
options.command === "dev"
command === "dev"
? config.srcDir
: path.join(config.distDir, config.publicDir),
config.indexHtml,
Expand All @@ -84,7 +85,7 @@ export function rsc<Context>(options: {
encoding: "utf8",
});
}
if (options.command === "start") {
if (command === "start") {
const destFile = path.join(
config.rootDir,
config.distDir,
Expand All @@ -97,25 +98,25 @@ export function rsc<Context>(options: {
} catch (e) {
return publicIndexHtml;
}
} else {
const vite = await getViteServer();
for (const item of vite.moduleGraph.idToModuleMap.values()) {
if (item.url === pathStr) {
return null;
}
}
// command === "dev"
const vite = await getViteServer();
for (const item of vite.moduleGraph.idToModuleMap.values()) {
if (item.url === pathStr) {
return null;
}
const destFile = path.join(config.rootDir, config.srcDir, pathStr);
try {
// check if exists?
const stats = await fsPromises.stat(destFile);
if (stats.isFile()) {
return null;
}
} catch (e) {
// does not exist
}
const destFile = path.join(config.rootDir, config.srcDir, pathStr);
try {
// check if exists?
const stats = await fsPromises.stat(destFile);
if (stats.isFile()) {
return null;
}
return vite.transformIndexHtml(pathStr, publicIndexHtml);
} catch (e) {
// does not exist
}
return vite.transformIndexHtml(pathStr, publicIndexHtml);
};

return async (req, res, next) => {
Expand All @@ -129,34 +130,28 @@ export function rsc<Context>(options: {
console.info("Cannot render RSC", err);
res.statusCode = 500;
}
if (options.command === "dev") {
if (command === "dev") {
res.end(String(err));
} else {
res.end();
}
};
let context: Context | undefined;
try {
context = options.unstable_prehook?.(req, res);
context = unstable_prehook?.(req, res);
} catch (e) {
handleError(e);
return;
}
if (options.ssr) {
if (ssr) {
try {
const htmlStr = await getHtmlStr(pathStr);
const result =
htmlStr &&
(await renderHtml(
config,
options.command,
pathStr,
htmlStr,
context,
));
(await renderHtml(config, command, pathStr, htmlStr, context));
if (result) {
const [readable, nextCtx] = result;
options.unstable_posthook?.(req, res, nextCtx as Context);
unstable_posthook?.(req, res, nextCtx as Context);
readable.on("error", handleError);
readable.pipe(res);
return;
Expand All @@ -176,19 +171,19 @@ export function rsc<Context>(options: {
input: decodeInput(pathStr.slice(basePrefix.length)),
method,
headers,
command: options.command,
command,
context,
stream: req,
});
options.unstable_posthook?.(req, res, nextCtx as Context);
unstable_posthook?.(req, res, nextCtx as Context);
readable.on("error", handleError);
readable.pipe(res);
} catch (e) {
handleError(e);
}
return;
}
if (options.command === "dev") {
if (command === "dev") {
const vite = await getViteServer();
// HACK re-export "?v=..." URL to avoid dual module hazard.
const fname = pathStr.startsWith(config.basePath + "@fs/")
Expand Down
2 changes: 1 addition & 1 deletion packages/waku/src/lib/middleware/rsc/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ const { createFromNodeStream } = RSDWClient;
type Entries = { default: ReturnType<typeof defineEntries> };

let lastViteServer: ViteDevServer | undefined;

const getViteServer = async () => {
if (lastViteServer) {
return lastViteServer;
Expand Down Expand Up @@ -326,6 +325,7 @@ export const renderHtml = async <Context>(
name,
};
}
// command === "dev"
const f = file.startsWith("@fs/")
? file.slice(3)
: path.join(config.rootDir, config.srcDir, file);
Expand Down
1 change: 0 additions & 1 deletion packages/waku/src/lib/middleware/rsc/worker-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ const handleGetBuildConfig = async (
};

let lastViteServer: ViteDevServer | undefined;

const getViteServer = async () => {
if (lastViteServer) {
return lastViteServer;
Expand Down

0 comments on commit b7a425f

Please sign in to comment.