/* eslint-disable @typescript-eslint/no-explicit-any */ import Router from "@koa/router"; import { FileManager } from "@sealcode/file-manager"; import Koa, { Context } from "koa"; import { Middlewares as SealiousMiddlewares } from "sealious"; import { Mountable } from "./page/mountable.js"; import { KoaResponsiveImageRouter } from "koa-responsive-image-router"; async function handleHtmlPromise(ctx: Context, next: Koa.Next) { await next(); if (ctx.body instanceof Promise) { ctx.body = await ctx.body; } ctx.set("content-type", "text/html;charset=utf-8"); } export function mount( router: Router, url: string | { rawURL: string }, mountable: Mountable, use_dummy_app = false, file_manager: FileManager | undefined = use_dummy_app ? new FileManager("/tmp", "/uploaded_files") : undefined ): void { const raw_url = typeof url === "string" ? url : url.rawURL; const args = use_dummy_app ? [ async (ctx: Context, next: any) => { // this dummy is a temporary solution it's ilustrating the ways that // sealgen is coupled with sealious. Definitely room for improvement in this // regard // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment ctx.$app = { fileManager: new FileManager("/tmp", "/uploaded_files"), imageRouter: new KoaResponsiveImageRouter({ staticPath: "/tmp", thumbnailSize: 10, cacheManagerResolutionThreshold: 10, imageStoragePath: "/tmp", smartCropStoragePath: "/tmp", }), // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment Logger: new Proxy( {}, { get: (_target: any, prop: any) => { if (prop === "info") { return () => {}; } else { return () => {}; } }, } ), getString: (x: string) => x, } as any; // eslint-disable-next-line @typescript-eslint/no-unsafe-call await next(); }, SealiousMiddlewares.parseBody(file_manager), handleHtmlPromise, ] : [ SealiousMiddlewares.extractContext(), SealiousMiddlewares.parseBody(file_manager), handleHtmlPromise, ]; router.use(raw_url, ...args); router.use(raw_url, async (_ctx, next) => { mountable.init(raw_url, router); await next(); }); // to automatically add trailing slashes: router.get(raw_url.slice(0, -1), async (ctx, next) => { const url2 = ctx.URL; if (!url2.pathname.endsWith("/")) { url2.pathname += "/"; ctx.redirect(url2.pathname + url2.search); } await next(); }); router.use(raw_url, async (ctx, next) => { ctx.set("content-type", "text/html;charset=utf-8"); const access_result = await mountable.canAccess(ctx); if (!access_result.canAccess) { ctx.status = 403; ctx.body = access_result.message || "no access"; return; } await next(); }); mountable.mount(router, raw_url); }