astro
Version:
Astro is a modern site builder with web best practices, performance, and DX front-of-mind.
68 lines (67 loc) • 2.17 kB
JavaScript
import { renderComponentToString } from "./component.js";
import { isAstroComponentFactory } from "./astro/index.js";
import { renderToAsyncIterable, renderToReadableStream, renderToString } from "./astro/render.js";
import { encoder } from "./common.js";
import { isDeno, isNode } from "./util.js";
async function renderPage(result, componentFactory, props, children, streaming, route) {
if (!isAstroComponentFactory(componentFactory)) {
result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
const pageProps = { ...props ?? {}, "server:root": true };
const str = await renderComponentToString(
result,
componentFactory.name,
componentFactory,
pageProps,
{},
true,
route
);
const bytes = encoder.encode(str);
return new Response(bytes, {
headers: new Headers([
["Content-Type", "text/html"],
["Content-Length", bytes.byteLength.toString()]
])
});
}
result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
let body;
if (streaming) {
if (isNode && !isDeno) {
const nodeBody = await renderToAsyncIterable(
result,
componentFactory,
props,
children,
true,
route
);
body = nodeBody;
} else {
body = await renderToReadableStream(result, componentFactory, props, children, true, route);
}
} else {
body = await renderToString(result, componentFactory, props, children, true, route);
}
if (body instanceof Response) return body;
const init = result.response;
const headers = new Headers(init.headers);
if (!streaming && typeof body === "string") {
body = encoder.encode(body);
headers.set("Content-Length", body.byteLength.toString());
}
let status = init.status;
if (route?.route === "/404") {
status = 404;
} else if (route?.route === "/500") {
status = 500;
}
if (status) {
return new Response(body, { ...init, headers, status });
} else {
return new Response(body, { ...init, headers });
}
}
export {
renderPage
};