import type { Context, Next } from "koa"; import { TempstreamJSX } from "tempstream"; import { JDD } from "@sealcode/jdd"; import type TheApp from "../../app.js"; import { registry } from "../../jdd-components/components.js"; import { makeJDDContext } from "../../jdd-context.js"; import type { RawJDDocument } from "@sealcode/jdd"; import { imageRouter } from "../../image-router.js"; import type { FilePointer } from "@sealcode/file-manager"; import html from "../../html.js"; import { tempstream } from "tempstream"; import { defaultHead } from "../../defaultHead.js"; import { BASE_URL, MULTI_DOMAIN_ENABLED } from "../../config.js"; interface ContextState { jddNames: string[]; } /* eslint-disable @typescript-eslint/consistent-type-assertions */ export const customUrlView = (app: TheApp) => async (ctx: Context & ContextState, next: Next) => { try { if (ctx.body) return; const main_domain = new URL(BASE_URL).hostname; let filter = { url: ctx.url.split("?")[0], }; if (MULTI_DOMAIN_ENABLED) { filter = { ...filter, ...(ctx.hostname !== main_domain ? { domain: ctx.hostname } : { domain: "" }), }; } const { items: [page], } = await app.collections.pages.list(ctx.$context).filter(filter).fetch(); const pageContent = Array.isArray(page?.get("content")) ? (page?.get("content") as RawJDDocument) : null; if (page && pageContent) { const jdd_context = makeJDDContext(ctx); const jdd = await JDD.fromStorage(registry, jdd_context, pageContent); const title = page.get("title"); const heading = page.get("heading"); const hideNavigation = page.get("hideNavigation") || false; const metaImage = (page.get("imageForMetadata") as FilePointer) || undefined; ctx.body = html({ ctx, title: title || ctx.$app.manifest.name, description: page.get("description") || "", css_clumps: jdd.getAllCSSClumps(), hideNavigation, htmlOptions: { showFooter: !hideNavigation, }, body: (
{heading?.trim() ?

{heading}

: ""} {jdd.render()}
), makeHead: (...args) => tempstream`${defaultHead(...args)}${jdd.renderEarlyAssets()}`, metaImage: metaImage ? await imageRouter.singleImage( await metaImage.getPath(), 400, "jpeg", false ) : "", }); } } catch (err) { // eslint-disable-next-line no-console console.log("error in custom url router middleware:", err); } finally { await next(); } };