Compare commits

...

5 commits

Author SHA1 Message Date
7194a0df13
Merge branch 'main' of ssh.creations.works:creations/bun_frontend_template into api
All checks were successful
Code quality checks / biome (push) Successful in 8s
2025-04-18 18:31:19 -04:00
a4c53c4bbb
fix ip logging issues
All checks were successful
Code quality checks / biome (push) Successful in 13s
2025-04-18 18:09:27 -04:00
1ce735f9ae
add workflow
All checks were successful
Code quality checks / biome (push) Successful in 12s
2025-04-11 04:08:17 -04:00
d6a25705b4
move to biomejs instead of eslint 2025-04-11 04:07:42 -04:00
f7082d05c1 Update README.md 2025-04-03 23:31:04 +00:00
12 changed files with 116 additions and 234 deletions

View file

@ -0,0 +1,24 @@
name: Code quality checks
on:
push:
pull_request:
jobs:
biome:
runs-on: docker
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Bun
run: |
curl -fsSL https://bun.sh/install | bash
export BUN_INSTALL="$HOME/.bun"
echo "$BUN_INSTALL/bin" >> $GITHUB_PATH
- name: Install Dependencies
run: bun install
- name: Run Biome with verbose output
run: bunx biome ci . --verbose

View file

@ -1,3 +1,3 @@
# bun frontend template # bun frontend template
a simle bun frontend starting point i made and use a simple bun frontend starting point i made and use

35
biome.json Normal file
View file

@ -0,0 +1,35 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": true,
"ignore": []
},
"formatter": {
"enabled": true,
"indentStyle": "tab",
"lineEnding": "lf"
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"indentStyle": "tab",
"lineEnding": "lf",
"jsxQuoteStyle": "double",
"semicolons": "always"
}
}
}

View file

@ -1,7 +1,6 @@
export const environment: Environment = { export const environment: Environment = {
port: parseInt(process.env.PORT || "8080", 10), port: Number.parseInt(process.env.PORT || "8080", 10),
host: process.env.HOST || "0.0.0.0", host: process.env.HOST || "0.0.0.0",
development: development:
process.env.NODE_ENV === "development" || process.env.NODE_ENV === "development" || process.argv.includes("--dev"),
process.argv.includes("--dev"),
}; };

View file

@ -1,132 +0,0 @@
import pluginJs from "@eslint/js";
import tseslintPlugin from "@typescript-eslint/eslint-plugin";
import tsParser from "@typescript-eslint/parser";
import prettier from "eslint-plugin-prettier";
import promisePlugin from "eslint-plugin-promise";
import simpleImportSort from "eslint-plugin-simple-import-sort";
import unicorn from "eslint-plugin-unicorn";
import unusedImports from "eslint-plugin-unused-imports";
import globals from "globals";
/** @type {import('eslint').Linter.FlatConfig[]} */
export default [
{
files: ["**/*.{js,mjs,cjs}"],
languageOptions: {
globals: globals.node,
},
...pluginJs.configs.recommended,
plugins: {
"simple-import-sort": simpleImportSort,
"unused-imports": unusedImports,
promise: promisePlugin,
prettier: prettier,
unicorn: unicorn,
},
rules: {
"eol-last": ["error", "always"],
"no-multiple-empty-lines": ["error", { max: 1, maxEOF: 1 }],
"no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"warn",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
},
],
"promise/always-return": "error",
"promise/no-return-wrap": "error",
"promise/param-names": "error",
"promise/catch-or-return": "error",
"promise/no-nesting": "warn",
"promise/no-promise-in-callback": "warn",
"promise/no-callback-in-promise": "warn",
"prettier/prettier": [
"error",
{
useTabs: true,
tabWidth: 4,
},
],
indent: ["error", "tab", { SwitchCase: 1 }],
"unicorn/filename-case": [
"error",
{
case: "camelCase",
},
],
},
},
{
files: ["**/*.{ts,tsx}"],
languageOptions: {
parser: tsParser,
globals: globals.node,
},
plugins: {
"@typescript-eslint": tseslintPlugin,
"simple-import-sort": simpleImportSort,
"unused-imports": unusedImports,
promise: promisePlugin,
prettier: prettier,
unicorn: unicorn,
},
rules: {
...tseslintPlugin.configs.recommended.rules,
quotes: ["error", "double"],
"eol-last": ["error", "always"],
"no-multiple-empty-lines": ["error", { max: 1, maxEOF: 1 }],
"no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"warn",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
},
],
"promise/always-return": "error",
"promise/no-return-wrap": "error",
"promise/param-names": "error",
"promise/catch-or-return": "error",
"promise/no-nesting": "warn",
"promise/no-promise-in-callback": "warn",
"promise/no-callback-in-promise": "warn",
"prettier/prettier": [
"error",
{
useTabs: true,
tabWidth: 4,
},
],
indent: ["error", "tab", { SwitchCase: 1 }],
"unicorn/filename-case": [
"error",
{
case: "camelCase",
},
],
"@typescript-eslint/explicit-function-return-type": ["error"],
"@typescript-eslint/explicit-module-boundary-types": ["error"],
"@typescript-eslint/typedef": [
"error",
{
arrowParameter: true,
variableDeclaration: true,
propertyDeclaration: true,
memberVariableDeclaration: true,
parameter: true,
},
],
},
},
];

View file

@ -5,25 +5,20 @@
"scripts": { "scripts": {
"start": "bun run src/index.ts", "start": "bun run src/index.ts",
"dev": "bun run --hot src/index.ts --dev", "dev": "bun run --hot src/index.ts --dev",
"lint": "eslint", "lint": "bunx biome check",
"lint:fix": "bun lint --fix", "lint:fix": "bunx biome check --fix",
"cleanup": "rm -rf logs node_modules bun.lockdb" "cleanup": "rm -rf logs node_modules bun.lockdb"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.23.0", "@types/bun": "^1.2.9",
"@types/bun": "^1.2.6", "@types/ejs": "^3.1.5",
"@typescript-eslint/eslint-plugin": "^8.28.0", "globals": "^16.0.0",
"@typescript-eslint/parser": "^8.28.0", "@biomejs/biome": "^1.9.4"
"eslint": "^9.23.0",
"eslint-plugin-prettier": "^5.2.5",
"eslint-plugin-promise": "^7.2.1",
"eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-unicorn": "^56.0.1",
"eslint-plugin-unused-imports": "^4.1.4",
"globals": "^15.15.0",
"prettier": "^3.5.3"
}, },
"peerDependencies": { "peerDependencies": {
"typescript": "^5.8.2" "typescript": "^5.8.3"
},
"dependencies": {
"ejs": "^3.1.10"
} }
} }

View file

@ -1,6 +1,6 @@
export function timestampToReadable(timestamp?: number): string { export function timestampToReadable(timestamp?: number): string {
const date: Date = const date: Date =
timestamp && !isNaN(timestamp) ? new Date(timestamp) : new Date(); timestamp && !Number.isNaN(timestamp) ? new Date(timestamp) : new Date();
if (isNaN(date.getTime())) return "Invalid Date"; if (Number.isNaN(date.getTime())) return "Invalid Date";
return date.toISOString().replace("T", " ").replace("Z", ""); return date.toISOString().replace("T", " ").replace("Z", "");
} }

View file

@ -1,15 +1,15 @@
import { environment } from "@config/environment"; import type { Stats } from "node:fs";
import { timestampToReadable } from "@helpers/char";
import type { Stats } from "fs";
import { import {
type WriteStream,
createWriteStream, createWriteStream,
existsSync, existsSync,
mkdirSync, mkdirSync,
statSync, statSync,
WriteStream, } from "node:fs";
} from "fs"; import { EOL } from "node:os";
import { EOL } from "os"; import { basename, join } from "node:path";
import { basename, join } from "path"; import { environment } from "@config/environment";
import { timestampToReadable } from "@helpers/char";
class Logger { class Logger {
private static instance: Logger; private static instance: Logger;
@ -37,7 +37,7 @@ class Logger {
mkdirSync(logDir, { recursive: true }); mkdirSync(logDir, { recursive: true });
} }
let addSeparator: boolean = false; let addSeparator = false;
if (existsSync(logFile)) { if (existsSync(logFile)) {
const fileStats: Stats = statSync(logFile); const fileStats: Stats = statSync(logFile);
@ -66,9 +66,9 @@ class Logger {
private extractFileName(stack: string): string { private extractFileName(stack: string): string {
const stackLines: string[] = stack.split("\n"); const stackLines: string[] = stack.split("\n");
let callerFile: string = ""; let callerFile = "";
for (let i: number = 2; i < stackLines.length; i++) { for (let i = 2; i < stackLines.length; i++) {
const line: string = stackLines[i].trim(); const line: string = stackLines[i].trim();
if (line && !line.includes("Logger.") && line.includes("(")) { if (line && !line.includes("Logger.") && line.includes("(")) {
callerFile = line.split("(")[1]?.split(")")[0] || ""; callerFile = line.split("(")[1]?.split(")")[0] || "";
@ -91,7 +91,7 @@ class Logger {
return { filename, timestamp: readableTimestamp }; return { filename, timestamp: readableTimestamp };
} }
public info(message: string | string[], breakLine: boolean = false): void { public info(message: string | string[], breakLine = false): void {
const stack: string = new Error().stack || ""; const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack); const { filename, timestamp } = this.getCallerInfo(stack);
@ -110,7 +110,7 @@ class Logger {
this.writeConsoleMessageColored(logMessageParts, breakLine); this.writeConsoleMessageColored(logMessageParts, breakLine);
} }
public warn(message: string | string[], breakLine: boolean = false): void { public warn(message: string | string[], breakLine = false): void {
const stack: string = new Error().stack || ""; const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack); const { filename, timestamp } = this.getCallerInfo(stack);
@ -131,7 +131,7 @@ class Logger {
public error( public error(
message: string | Error | (string | Error)[], message: string | Error | (string | Error)[],
breakLine: boolean = false, breakLine = false,
): void { ): void {
const stack: string = new Error().stack || ""; const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack); const { filename, timestamp } = this.getCallerInfo(stack);
@ -161,7 +161,7 @@ class Logger {
bracketMessage2: string, bracketMessage2: string,
message: string | string[], message: string | string[],
color: string, color: string,
breakLine: boolean = false, breakLine = false,
): void { ): void {
const stack: string = new Error().stack || ""; const stack: string = new Error().stack || "";
const { timestamp } = this.getCallerInfo(stack); const { timestamp } = this.getCallerInfo(stack);
@ -189,7 +189,7 @@ class Logger {
private writeConsoleMessageColored( private writeConsoleMessageColored(
logMessageParts: ILogMessageParts, logMessageParts: ILogMessageParts,
breakLine: boolean = false, breakLine = false,
): void { ): void {
const logMessage: string = Object.keys(logMessageParts) const logMessage: string = Object.keys(logMessageParts)
.map((key: string) => { .map((key: string) => {

View file

@ -3,11 +3,7 @@ import { logger } from "@helpers/logger";
import { serverHandler } from "@/server"; import { serverHandler } from "@/server";
async function main(): Promise<void> { async function main(): Promise<void> {
try {
serverHandler.initialize(); serverHandler.initialize();
} catch (error) {
throw error;
}
} }
main().catch((error: Error) => { main().catch((error: Error) => {

View file

@ -1,3 +1,4 @@
import { resolve } from "node:path";
import { environment } from "@config/environment"; import { environment } from "@config/environment";
import { logger } from "@helpers/logger"; import { logger } from "@helpers/logger";
import { import {
@ -6,7 +7,6 @@ import {
type MatchedRoute, type MatchedRoute,
type Serve, type Serve,
} from "bun"; } from "bun";
import { resolve } from "path";
import { webSocketHandler } from "@/websocket"; import { webSocketHandler } from "@/websocket";
@ -73,21 +73,16 @@ class ServerHandler {
if (await file.exists()) { if (await file.exists()) {
const fileContent: ArrayBuffer = await file.arrayBuffer(); const fileContent: ArrayBuffer = await file.arrayBuffer();
const contentType: string = const contentType: string = file.type || "application/octet-stream";
file.type || "application/octet-stream";
return new Response(fileContent, { return new Response(fileContent, {
headers: { "Content-Type": contentType }, headers: { "Content-Type": contentType },
}); });
} else { }
logger.warn(`File not found: ${filePath}`); logger.warn(`File not found: ${filePath}`);
return new Response("Not Found", { status: 404 }); return new Response("Not Found", { status: 404 });
}
} catch (error) { } catch (error) {
logger.error([ logger.error([`Error serving static file: ${pathname}`, error as Error]);
`Error serving static file: ${pathname}`,
error as Error,
]);
return new Response("Internal Server Error", { status: 500 }); return new Response("Internal Server Error", { status: 500 });
} }
} }
@ -113,8 +108,7 @@ class ServerHandler {
try { try {
const routeModule: RouteModule = await import(filePath); const routeModule: RouteModule = await import(filePath);
const contentType: string | null = const contentType: string | null = request.headers.get("Content-Type");
request.headers.get("Content-Type");
const actualContentType: string | null = contentType const actualContentType: string | null = contentType
? contentType.split(";")[0].trim() ? contentType.split(";")[0].trim()
: null; : null;
@ -141,9 +135,7 @@ class ServerHandler {
if ( if (
(Array.isArray(routeModule.routeDef.method) && (Array.isArray(routeModule.routeDef.method) &&
!routeModule.routeDef.method.includes( !routeModule.routeDef.method.includes(request.method)) ||
request.method,
)) ||
(!Array.isArray(routeModule.routeDef.method) && (!Array.isArray(routeModule.routeDef.method) &&
routeModule.routeDef.method !== request.method) routeModule.routeDef.method !== request.method)
) { ) {
@ -168,9 +160,7 @@ class ServerHandler {
if (Array.isArray(expectedContentType)) { if (Array.isArray(expectedContentType)) {
matchesAccepts = matchesAccepts =
expectedContentType.includes("*/*") || expectedContentType.includes("*/*") ||
expectedContentType.includes( expectedContentType.includes(actualContentType || "");
actualContentType || "",
);
} else { } else {
matchesAccepts = matchesAccepts =
expectedContentType === "*/*" || expectedContentType === "*/*" ||
@ -209,10 +199,7 @@ class ServerHandler {
} }
} }
} catch (error: unknown) { } catch (error: unknown) {
logger.error([ logger.error([`Error handling route ${request.url}:`, error as Error]);
`Error handling route ${request.url}:`,
error as Error,
]);
response = Response.json( response = Response.json(
{ {
@ -234,15 +221,15 @@ class ServerHandler {
); );
} }
const headers: Headers = response.headers; const headers = request.headers;
let ip: string | null = server.requestIP(request)?.address || null; let ip = server.requestIP(request)?.address;
if (!ip) { if (!ip || ip.startsWith("172.") || ip === "127.0.0.1") {
ip = ip =
headers.get("CF-Connecting-IP") || headers.get("CF-Connecting-IP")?.trim() ||
headers.get("X-Real-IP") || headers.get("X-Real-IP")?.trim() ||
headers.get("X-Forwarded-For") || headers.get("X-Forwarded-For")?.split(",")[0].trim() ||
null; "unknown";
} }
logger.custom( logger.custom(

View file

@ -1,5 +1,5 @@
import { logger } from "@helpers/logger"; import { logger } from "@helpers/logger";
import { type ServerWebSocket } from "bun"; import type { ServerWebSocket } from "bun";
class WebSocketHandler { class WebSocketHandler {
public handleMessage(ws: ServerWebSocket, message: string): void { public handleMessage(ws: ServerWebSocket, message: string): void {
@ -20,11 +20,7 @@ class WebSocketHandler {
} }
} }
public handleClose( public handleClose(ws: ServerWebSocket, code: number, reason: string): void {
ws: ServerWebSocket,
code: number,
reason: string,
): void {
logger.warn(`WebSocket closed with code ${code}, reason: ${reason}`); logger.warn(`WebSocket closed with code ${code}, reason: ${reason}`);
} }
} }

View file

@ -2,28 +2,14 @@
"compilerOptions": { "compilerOptions": {
"baseUrl": "./", "baseUrl": "./",
"paths": { "paths": {
"@/*": [ "@/*": ["src/*"],
"src/*" "@config/*": ["config/*"],
], "@types/*": ["types/*"],
"@config/*": [ "@helpers/*": ["src/helpers/*"]
"config/*"
],
"@types/*": [
"types/*"
],
"@helpers/*": [
"src/helpers/*"
]
}, },
"typeRoots": [ "typeRoots": ["./src/types", "./node_modules/@types"],
"./src/types",
"./node_modules/@types"
],
// Enable latest features // Enable latest features
"lib": [ "lib": ["ESNext", "DOM"],
"ESNext",
"DOM"
],
"target": "ESNext", "target": "ESNext",
"module": "ESNext", "module": "ESNext",
"moduleDetection": "force", "moduleDetection": "force",
@ -41,11 +27,7 @@
// Some stricter flags (disabled by default) // Some stricter flags (disabled by default)
"noUnusedLocals": false, "noUnusedLocals": false,
"noUnusedParameters": false, "noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false, "noPropertyAccessFromIndexSignature": false
}, },
"include": [ "include": ["src", "types", "config"]
"src",
"types",
"config"
],
} }