import fp from "fastify-plugin"; import dateTime from "./date-time.js"; import { bold, blue, dim, yellow, red, cyan, green } from "femtocolor"; /* eslint-disable @typescript-eslint/no-var-requires */ const ms = require("ms") as (val: number, options?: object) => string; const colorOptions = ( require("femtocolor") as { options: { enabled: boolean } } ).options; /* eslint-enable @typescript-eslint/no-var-requires */ // femtocolor requires process.env.TERM (POSIX) to enable colors; Windows terminals don't set it. // Fall back to Node's own color-depth check, which handles Windows Terminal via WT_SESSION. if ( !colorOptions.enabled && process.stdout.isTTY && process.stdout.hasColors() ) { colorOptions.enabled = true; } const EOL = "\n"; const colorCodes: Record string> = { 5: red, 4: yellow, 3: cyan, 2: green, }; const getColor = (status: number) => colorCodes[Math.trunc(status / 100)] ?? ((s: string) => s); export const header = blue("⚡︎dev-server"); const log = (msg: string): void => { process.stdout.write(`[${dateTime()}] ${msg}` + EOL); }; export const responseLogger = fp( async (server: any, { silent = false }: { silent?: boolean } = {}) => { if (silent) return; const logResponse = async (req: any, reply: any) => { const status: number = reply.statusCode; const c = getColor(status); const timing = ms(Math.round(reply.elapsedTime)) || ""; log( bold(c(req.method)) + " " + req.url + c(" • ") + dim(status + " • " + timing), ); }; server.addHook("onResponse", logResponse); }, ); export const logDir = (dir: string): void => log(header + " serving " + bold(dir)); export const logSpa = (spaFile: string): void => log(header + " using fallback file " + bold(spaFile)); export const logProxy = (from: string, to: string): void => log( header + " proxying from " + bold(yellow(from)) + " to " + bold(yellow(to)), ); export const logListening = (host: string, port: number): void => log(header + " listening on " + bold(green(`http://${host}:${port}`)));