0.1.5Updated 6 months ago
import { defineConfig, createHandler, type FreshConfig, type ResolvedFreshConfig, type ServeHandlerInfo, type Manifest } from "$fresh/server.ts";
import { getInternalFreshState } from "$fresh/src/server/config.ts";

import { create_manifest } from "@infinity-beyond/modules/networking/create_manifest.ts";
import { manifest } from "@infinity-beyond/dist/manifest.ts";
import { join, toFileUrl } from "https://deno.land/std@0.216.0/path/mod.ts";

import tailwind from "jsr:@pakornv/fresh-plugin-tailwindcss@^1.0.2";

interface ServerConfig extends FreshConfig {
  dev?: boolean
}

export async function freshHandler(config: ServerConfig = {}) {
  config = defineConfig({
    ...config,
    plugins: [
      tailwind()
    ]
  })

  console.log(`Loading plugins...`);
  console.log(`  '- ${config.plugins!.length} loaded\n`);

  console.log(`Building manifest...`);
  const client_manifest = await create_manifest(toFileUrl(join(Deno.cwd(), 'app/any.ts')).href);

  console.log(`  '- ${Object.keys(client_manifest.routes).length} client routes`);
  console.log(`  '- ${Object.keys(client_manifest.islands).length} client islands`);
  console.log(`  '- ${Object.keys(manifest.routes).length} infinity routes`);
  console.log(`  '- ${Object.keys(manifest.islands).length} infinity islands`);

  for(const [route, route_import] of Object.entries(manifest.routes)) {
    client_manifest.routes[route] = route_import;
  }
  for(const [island, island_import] of Object.entries(manifest.islands)) {
    client_manifest.islands[island] = island_import;
  }

  console.log(`  '- fin`);
  console.log(`Manifest updated for ${Object.keys(client_manifest.routes).length} routes and ${Object.keys(client_manifest.islands).length} islands\n`);

  const ctx = await getInternalFreshState(client_manifest, config);

  return [await createHandler(client_manifest, ctx.config), ctx.config, client_manifest] as [(req: Request, connInfo?: ServeHandlerInfo) => Promise<Response>, ResolvedFreshConfig, Manifest];
}