All files fastify-adapter.ts

81.48% Statements 88/108
58.94% Branches 56/95
100% Functions 14/14
81.13% Lines 86/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                    1x 1x   1x 1x 1x 1x   1x 6x     6x     6x   1x 1x 1x 1x       1x 1x 1x                       1x     1x 7x                                         7x 1x     6x 6x   6x 6x   6x 6x 6x   6x 6x 6x 6x   6x       1x 1x 1x     1x 1x       3x       3x 3x 1x     2x 2x   2x       2x 2x       2x 2x 2x       2x 2x 1x 1x 1x   1x 1x   1x         3x       3x 1x     2x 2x 1x 1x   1x 1x           1x       2x 1x 1x   1x       2x 1x 1x 1x   1x 1x     1x                     1x                     1x 1x 1x   1x       1x      
import { HttpMethod } from "@xtaskjs/common";
import {
  FastifyAdapterOptions,
  HttpAdapter,
  HttpRequestHandler,
  HttpRequestLike,
  HttpResponseLike,
  HttpServerOptions,
  HttpViewResult,
} from "./types";
import { access, readFile } from "fs/promises";
import path from "path";
 
const SUPPORTED_METHODS: HttpMethod[] = ["GET", "POST", "PATCH", "DELETE"];
const DEFAULT_VIEWS_FOLDER = "views";
const DEFAULT_PUBLIC_FOLDER = "public";
const DEFAULT_FILE_EXTENSION = ".html";
 
const withLeadingSlash = (value: string): string => {
  Iif (!value) {
    return "/";
  }
  return value.startsWith("/") ? value : `/${value}`;
};
 
const withLeadingDot = (value: string): string => (value.startsWith(".") ? value : `.${value}`);
 
const interpolateTemplate = (template: string, model: Record<string, any>): string => {
  return template.replace(/{{\s*([\w.]+)\s*}}/g, (_match, key: string) => {
    const value = key.split(".").reduce<any>((acc, segment) => acc?.[segment], model);
    return value === undefined || value === null ? "" : String(value);
  });
};
 
const getContentType = (filePath: string): string => {
  const extension = path.extname(filePath).toLowerCase();
  const contentTypes: Record<string, string> = {
    ".css": "text/css; charset=utf-8",
    ".js": "application/javascript; charset=utf-8",
    ".json": "application/json; charset=utf-8",
    ".html": "text/html; charset=utf-8",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".svg": "image/svg+xml",
    ".ico": "image/x-icon",
    ".webp": "image/webp",
  };
  return contentTypes[extension] || "application/octet-stream";
};
 
export class FastifyAdapter implements HttpAdapter {
  public readonly type = "fastify" as const;
  private readonly app: any;
  private readonly templateRenderer?: (
    template: string,
    model: Record<string, any>,
    context: { req: HttpRequestLike; res: HttpResponseLike }
  ) => string | Promise<string>;
  private readonly nativeTemplateRenderer?: (
    res: HttpResponseLike,
    template: string,
    model: Record<string, any>
  ) => Promise<any>;
  private readonly staticEnabled: boolean;
  private readonly publicPath: string;
  private readonly publicPrefix: string;
  private readonly resolvedPublicPath: string;
  private readonly viewsPath: string;
  private readonly fileExtension: string;
  private readonly resolvedViewsPath: string;
 
  constructor(app: any, options?: FastifyAdapterOptions) {
    if (!app || typeof app.route !== "function" || typeof app.listen !== "function") {
      throw new Error("FastifyAdapter requires a valid fastify instance");
    }
 
    const templateEngine = options?.templateEngine;
    const staticFiles = options?.staticFiles;
 
    this.templateRenderer = templateEngine?.render;
    this.nativeTemplateRenderer = templateEngine?.nativeRender;
 
    this.viewsPath = templateEngine?.viewsPath || path.join(process.cwd(), DEFAULT_VIEWS_FOLDER);
    this.fileExtension = withLeadingDot(templateEngine?.fileExtension || DEFAULT_FILE_EXTENSION);
    this.resolvedViewsPath = path.resolve(this.viewsPath);
 
    this.staticEnabled = staticFiles?.enabled !== false;
    this.publicPath = staticFiles?.publicPath || path.join(process.cwd(), DEFAULT_PUBLIC_FOLDER);
    this.publicPrefix = withLeadingSlash(staticFiles?.urlPrefix || "/");
    this.resolvedPublicPath = path.resolve(this.publicPath);
 
    this.app = app;
  }
 
  private async renderFileTemplate(template: string, model: Record<string, any>): Promise<string> {
    const fullTemplateName = path.extname(template) ? template : `${template}${this.fileExtension}`;
    const templatePath = path.resolve(path.join(this.viewsPath, fullTemplateName));
    Iif (!templatePath.startsWith(this.resolvedViewsPath)) {
      throw new Error("Template path is outside configured views directory");
    }
    const templateFile = await readFile(templatePath, "utf-8");
    return interpolateTemplate(templateFile, model);
  }
 
  private async tryServeStatic(request: any, reply: any): Promise<boolean> {
    Iif (!this.staticEnabled) {
      return false;
    }
 
    const method = String(request?.method || "GET").toUpperCase();
    if (method !== "GET") {
      return false;
    }
 
    const rawUrl = String(request?.url || "/");
    const pathname = new URL(rawUrl, "http://localhost").pathname;
 
    Iif (this.publicPrefix !== "/" && !pathname.startsWith(this.publicPrefix)) {
      return false;
    }
 
    const relativePath = this.publicPrefix === "/" ? pathname : pathname.slice(this.publicPrefix.length);
    Iif (!relativePath || relativePath === "/") {
      return false;
    }
 
    const decodedRelativePath = decodeURIComponent(relativePath);
    const staticFilePath = path.resolve(path.join(this.publicPath, decodedRelativePath));
    Iif (!staticFilePath.startsWith(this.resolvedPublicPath)) {
      return false;
    }
 
    try {
      await access(staticFilePath);
      const content = await readFile(staticFilePath);
      Eif (typeof reply.header === "function") {
        reply.header("content-type", getContentType(staticFilePath));
      }
      reply.send(content);
      return true;
    } catch {
      return false;
    }
  }
 
  registerRequestHandler(handler: HttpRequestHandler): void {
    this.app.route({
      method: ["GET", "POST", "PATCH", "DELETE"],
      url: "*",
      handler: async (request: any, reply: any) => {
        if (await this.tryServeStatic(request, reply)) {
          return;
        }
 
        const method = (request.method || "GET").toUpperCase() as HttpMethod;
        if (!SUPPORTED_METHODS.includes(method)) {
          reply.code(405).send("Method Not Allowed");
          return;
        }
        const path = request.url || "/";
        await handler(method, path, request, reply);
      },
    });
  }
 
  async listen(options: Required<HttpServerOptions>): Promise<void> {
    await this.app.listen({ port: options.port, host: options.host });
  }
 
  async renderView(req: HttpRequestLike, res: HttpResponseLike, payload: HttpViewResult): Promise<void> {
    if (payload.statusCode && typeof res.code === "function") {
      res.code(payload.statusCode);
    } else Iif (payload.statusCode && typeof res.status === "function") {
      res.status(payload.statusCode);
    } else Iif (payload.statusCode) {
      res.statusCode = payload.statusCode;
    }
 
    if (this.templateRenderer) {
      const html = await this.templateRenderer(payload.template, payload.model || {}, { req, res });
      Eif (typeof res.header === "function") {
        res.header("content-type", "text/html; charset=utf-8");
      }
      res.send?.(html);
      return;
    }
 
    Iif (this.nativeTemplateRenderer) {
      const output = await this.nativeTemplateRenderer(res, payload.template, payload.model || {});
      if (typeof output === "string") {
        if (typeof res.header === "function") {
          res.header("content-type", "text/html; charset=utf-8");
        }
        res.send?.(output);
      }
      return;
    }
 
    Iif (typeof res.view === "function") {
      const output = await res.view(payload.template, payload.model || {});
      if (typeof output === "string") {
        if (typeof res.header === "function") {
          res.header("content-type", "text/html; charset=utf-8");
        }
        res.send?.(output);
      }
      return;
    }
 
    const html = await this.renderFileTemplate(payload.template, payload.model || {});
    Eif (typeof res.header === "function") {
      res.header("content-type", "text/html; charset=utf-8");
    }
    res.send?.(html);
  }
 
  async close(): Promise<void> {
    await this.app.close();
  }
}