### Standard Express Server Implementation Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md A basic server example using the standard Express framework. This serves as a baseline for comparison, demonstrating the typical setup for an Express application. ```javascript const express = require("express"); // Standard const app = express(); app.get("/", (req, res) => { res.json({ message: "Standard Express" }); }); app.listen(3000); ``` -------------------------------- ### Run Individual LiteX Development Commands Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Provides commands to start only the backend server with hot reloading using tsx watch, start only the frontend development server using Vite, build the frontend or backend individually, build all project components, and start the production server. ```bash # Start only backend server (with tsx watch) npm run dev:server # Start only frontend dev server (with Vite) npm run dev:vite # Build frontend only npm run build:vite # Build backend only npm run build:server # Build everything npm run build # Start production server npm start ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Copies the example environment file and instructs to edit it with specific configurations. This step is crucial for setting up server ports, database connections, and other environment-specific settings. It assumes a `.env.example` file exists. ```bash # Copy environment template copy .env.example .env # Edit .env file with your configuration ``` -------------------------------- ### Hyper-Express Server Implementation Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md An example of a server built with Hyper-Express. This code illustrates the distinct API and syntax compared to Express, noting the different parameter names and server initialization/listening methods. ```javascript const HyperExpress = require("hyper-express"); // Different API const webserver = new HyperExpress.Server(); // Different syntax webserver.get("/", (request, response) => { // Different parameter names response.json({ message: "Different API" }); }); webserver.listen(3000); // Different approach ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Installs all necessary project dependencies using npm. This is typically the first step after cloning the repository. It requires Node.js and npm to be installed. ```bash npm install ``` -------------------------------- ### PWA Install Prompt Handling (JavaScript) Source: https://github.com/arghoritma/litex/blob/main/resources/views/index.html Handles the 'beforeinstallprompt' event to allow users to install the PWA. It shows an 'Install App' button when the prompt is available and triggers the installation flow when the button is clicked. The button is dynamically created and appended to the body. ```javascript // PWA Install Prompt let deferredPrompt; window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); deferredPrompt = e; showInstallButton(); }); function showInstallButton() { // Create install button if not exists if (!document.getElementById("pwa-install-btn")) { const installBtn = document.createElement("button"); installBtn.id = "pwa-install-btn"; installBtn.innerHTML = "📱 Install App"; installBtn.className = "btn-secondary fast-hover"; installBtn.style.position = "fixed"; installBtn.style.bottom = "20px"; installBtn.style.right = "20px"; installBtn.style.zIndex = "1000"; installBtn.style.fontSize = "14px"; installBtn.style.padding = "10px 16px"; installBtn.addEventListener("click", async () => { if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; console.log("⚡ LiteX PWA: Install prompt outcome:", outcome); deferredPrompt = null; installBtn.remove(); } }); document.body.appendChild(installBtn); } } ``` -------------------------------- ### Start LiteX Development Servers Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Starts both the frontend (Vite) and backend (LiteX Backend Server) in development mode simultaneously. This command is used for active development, providing hot reloading for instant updates. ```bash # Start both frontend and backend in development mode npm run dev ``` -------------------------------- ### Quick Start LiteX App Creation (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command quickly sets up a new LiteX project using npx, downloads necessary files, and then navigates into the project directory to start the development server. ```bash npx create-litex-app project-name cd project-name npm run dev ``` -------------------------------- ### Basic HTTP Server Setup with Ultimate-Express Source: https://github.com/arghoritma/litex/blob/main/ultimate-express.md Illustrates the simplified HTTP server setup using ultimate-express's `app.listen()` method, which replaces manual creation of an HTTP server as done with the standard express framework. ```javascript const express = require("ultimate-express"); const app = express(); app.listen(3000, () => { console.log("Server is running on port 3000"); }); ``` -------------------------------- ### PWA Install Prompt for Inertia Pages Source: https://github.com/arghoritma/litex/blob/main/dist/views/inertia.html This code handles the PWA 'Add to Home Screen' prompt for Inertia pages. It listens for the 'beforeinstallprompt' event, creates and styles an install button dynamically if it doesn't exist, and prompts the user to install the app when the button is clicked. It also removes the button upon successful installation. ```javascript let deferredPrompt; window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); deferredPrompt = e; if (!document.getElementById("pwa-install-btn")) { const installBtn = document.createElement("button"); installBtn.id = "pwa-install-btn"; installBtn.innerHTML = "📱 Install LiteX"; installBtn.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 20px; border-radius: 25px; font-weight: 600; font-size: 14px; cursor: pointer; z-index: 1000; box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3); transition: all 0.3s ease; `; installBtn.addEventListener("mouseover", () => { installBtn.style.transform = "translateY(-2px)"; installBtn.style.boxShadow = "0 12px 35px rgba(102, 126, 234, 0.4)"; }); installBtn.addEventListener("mouseout", () => { installBtn.style.transform = "translateY(0)"; installBtn.style.boxShadow = "0 8px 25px rgba(102, 126, 234, 0.3)"; }); installBtn.addEventListener("click", async () => { if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; console.log("⚡ LiteX PWA: Install prompt outcome:", outcome); deferredPrompt = null; installBtn.remove(); } }); document.body.appendChild(installBtn); } }); window.addEventListener("appinstalled", () => { const installBtn = document.getElementById("pwa-install-btn"); if (installBtn) { installBtn.remove(); } console.log("⚡ LiteX PWA: App installed successfully"); }); ``` -------------------------------- ### Start Development Server and Build for Production Source: https://context7.com/arghoritma/litex/llms.txt Commands for managing the development server and building the project for production. 'npm run dev' starts both the backend and Vite frontend dev servers. 'npm run build' prepares the application for deployment by compiling assets and code. 'npm start' runs the production build. ```bash # Start development server (with hot reload) npm run dev # Starts both Vite dev server (port 3000) and backend (port 5555) # Build for production npm run build # 1. Cleans build directory # 2. Builds frontend assets with Vite # 3. Compiles TypeScript # 4. Copies dist and public folders to build # Start production server npm start # Runs: node build/server.js ``` -------------------------------- ### Home Controller Example in TypeScript Source: https://github.com/arghoritma/litex/blob/main/dist/views/index.html This snippet demonstrates how to set up a Home Controller in LiteX using TypeScript. It imports necessary modules from 'ultimate-express' and '@inertiajs/svelte' for request handling and rendering. The controller defines an 'index' method to render the 'Home' view with a dynamic title. It also includes an example of setting up a GET route for the home page using a 'router' object. ```typescript // ⚡ Ultra-fast setup import { Response, Request } from "ultimate-express"; import { render } from "@inertiajs/svelte"; class HomeController { async index(req: Request, res: Response) { return render(res, "Home", { title: "⚡ LiteX Speed!" }); } } export default new HomeController(); // 🚀 Route setup router.get("/", HomeController.index); ``` -------------------------------- ### PWA Install Prompt for Inertia Pages (JavaScript) Source: https://github.com/arghoritma/litex/blob/main/resources/views/inertia.html This JavaScript code implements a 'beforeinstallprompt' event listener to display an install button for the LiteX PWA on Inertia pages. It allows users to install the application by clicking the button, which triggers the browser's native install prompt. The code dynamically creates and styles the button, and handles its removal after installation or if the user dismisses the prompt. ```javascript // PWA Install Prompt for Inertia pages let deferredPrompt; window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); deferredPrompt = e; // Show install prompt if not on main page if (!document.getElementById("pwa-install-btn")) { const installBtn = document.createElement("button"); installBtn.id = "pwa-install-btn"; installBtn.innerHTML = "📱 Install LiteX"; installBtn.style.cssText = ` position: fixed; bottom: 20px; right: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 20px; border-radius: 25px; font-weight: 600; font-size: 14px; cursor: pointer; z-index: 1000; box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3); transition: all 0.3s ease; ` installBtn.addEventListener("mouseover", () => { installBtn.style.transform = "translateY(-2px)"; installBtn.style.boxShadow = "0 12px 35px rgba(102, 126, 234, 0.4)"; }); installBtn.addEventListener("mouseout", () => { installBtn.style.transform = "translateY(0)"; installBtn.style.boxShadow = "0 8px 25px rgba(102, 126, 234, 0.3)"; }); installBtn.addEventListener("click", async () => { if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; console.log("⚡ LiteX PWA: Install prompt outcome:", outcome); deferredPrompt = null; installBtn.remove(); } }); document.body.appendChild(installBtn); } }); // Hide install button when app is installed window.addEventListener("appinstalled", () => { const installBtn = document.getElementById("pwa-install-btn"); if (installBtn) { installBtn.remove(); } console.log("⚡ LiteX PWA: App installed successfully"); }); ``` -------------------------------- ### LiteX Express API Compatible Server Example Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md Demonstrates a server implemented using LiteX (Ultimate Express), showcasing its 100% Express API compatibility. This snippet highlights how minimal code changes are needed to migrate from Express to LiteX. ```javascript const express = require("ultimate-express"); // Only line that changes! const app = express(); app.get("/", (req, res) => { res.json({ message: "Same API as Express!" }); }); app.listen(3000); // Exact same as Express ``` -------------------------------- ### Reinstall Dependencies in LiteX Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Instructions for performing a clean installation of project dependencies. This involves removing the `node_modules` directory and `package-lock.json` file, followed by running `npm install` again. Useful for resolving complex dependency issues. ```bash # Clean install rm -rf node_modules package-lock.json npm install ``` -------------------------------- ### Install Dependencies and Run Database Migrations Source: https://context7.com/arghoritma/litex/llms.txt Standard npm commands to install project dependencies and apply the latest database migrations using Knex.js. 'npm install' fetches all necessary packages, and 'npx knex migrate:latest' ensures the database schema is up-to-date. ```bash # Install dependencies npm install # Run database migrations npx knex migrate:latest ``` -------------------------------- ### Manual Individual Framework Testing with wrk Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md Perform manual performance testing on individual frameworks using the 'wrk' benchmarking tool. This method involves starting each server and then running 'wrk' against their respective ports to measure requests per second, latency, and transfer rates. ```bash # Terminal 1-4: Start all servers node litex-test.js # Port 3006 node express-test.js # Port 3008 node hyper-express.js # Port 3009 node node-test.js # Port 3007 # Terminal 5: Run benchmarks wrk -t12 -c400 -d30s http://localhost:3006 # LiteX wrk -t12 -c400 -d30s http://localhost:3008 # Express wrk -t12 -c400 -d30s http://localhost:3009 # Hyper-Express wrk -t12 -c400 -d30s http://localhost:3007 # Node.js ``` -------------------------------- ### Example Controller for Creating a Post Source: https://context7.com/arghoritma/litex/llms.txt A TypeScript example demonstrating how to handle a request to create a new post. It extracts data from the request body, generates a slug, and inserts the new post into the 'posts' table using a database utility. ```typescript // Usage in controller async function createPost(request: Request, response: Response) { const { title, content } = request.body; const post = { id: randomUUID(), user_id: request.user.id, title: title, content: content, slug: title.toLowerCase().replace(/\s+/g, "-"), is_published: false, created_at: Date.now(), updated_at: Date.now() }; await DB.table("posts").insert(post); return response.redirect("/posts"); } ``` -------------------------------- ### Start Development Server (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command starts the LiteX development server. It typically runs the backend with nodemon for auto-reloading and the Vite development server for frontend assets. ```bash npm run dev ``` -------------------------------- ### Copy Environment File (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command copies the example environment file to a new file named '.env'. This is a standard practice for setting up application-specific configurations before running the application. ```bash cp .env.example .env ``` -------------------------------- ### Benchmark Execution with NPM Scripts Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md Utilize NPM scripts for executing framework benchmarks. This modern approach allows for convenient triggering of both complete sequential tests for accuracy and quick parallel tests for speed. ```bash cd benchmark npm run benchmark:complete ``` ```bash cd benchmark npm run benchmark:parallel ``` -------------------------------- ### Run Specific Development Server Instances Source: https://context7.com/arghoritma/litex/llms.txt These commands allow running either the backend or frontend development server independently. 'npm run dev:server' starts only the backend, while 'npm run dev:vite' starts only the Vite frontend development server. ```bash # Run only backend dev server npm run dev:server # Run only frontend dev server npm run dev:vite ``` -------------------------------- ### Benchmark Execution with PowerShell Scripts Source: https://github.com/arghoritma/litex/blob/main/benchmark/COMPLETE-GUIDE.md Execute comprehensive benchmarks using PowerShell scripts. These scripts automate the testing process for different frameworks, offering both sequential (accurate) and parallel (fast) execution options. ```bash cd benchmark powershell -ExecutionPolicy Bypass -File complete-benchmark.ps1 ``` ```bash cd benchmark powershell -ExecutionPolicy Bypass -File parallel-all-frameworks.ps1 ``` -------------------------------- ### Home Controller Setup in TypeScript Source: https://github.com/arghoritma/litex/blob/main/resources/views/index.html This snippet demonstrates how to set up a Home Controller using TypeScript with LiteX. It utilizes Ultimate Express for request and response handling and @inertiajs/svelte for rendering. The controller defines an index method to handle incoming requests and render a 'Home' view with a dynamic title. ```typescript // ⚡ Ultra-fast setup import { Response, Request } from "ultimate-express"; import { render } from "@inertiajs/svelte"; class HomeController { async index(req: Request, res: Response) { return render(res, "Home", { title: "⚡ LiteX Speed!" }); } } export default new HomeController(); // 🚀 Route setup router.get("/", HomeController.index); ``` -------------------------------- ### Docker Compose for Development (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command initiates the LiteX application in development mode using Docker Compose. It assumes Docker and Docker Compose are installed and the necessary configuration files are present. ```bash docker-compose up -d ``` -------------------------------- ### HTTPS Server Setup with Ultimate-Express Source: https://github.com/arghoritma/litex/blob/main/ultimate-express.md Demonstrates how to set up an HTTPS server using ultimate-express, passing SSL certificate options directly to the express constructor. This differs from the traditional Node.js https module approach. ```javascript const express = require("ultimate-express"); const app = express({ uwsOptions: { // https://unetworking.github.io/uWebSockets.js/generated/interfaces/AppOptions.html key_file_name: "path/to/key.pem", cert_file_name: "path/to/cert.pem", }, }); app.listen(3000, () => { console.log("Server is running on port 3000"); }); ``` -------------------------------- ### Troubleshoot Port Conflicts in LiteX Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Provides instructions on how to resolve port conflicts by changing the backend and frontend development server ports in the `.env` file. This is useful when the default ports are already in use. ```bash PORT=5556 # Change backend port VITE_PORT=3001 # Change frontend port ``` -------------------------------- ### Set Environment Variables for LiteX Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Illustrates common environment variables used by the LiteX project, including ports for the backend and frontend development servers, and the database connection URL. These are typically set in the `.env` file. ```bash # Server PORT=5555 # Backend server port NODE_ENV=development # Environment mode # Frontend VITE_PORT=3000 # Vite dev server port # Database DATABASE_URL=./dev.sqlite3 # Add other variables as needed... ``` -------------------------------- ### Ultimate Express Server Setup with Middleware Source: https://context7.com/arghoritma/litex/llms.txt This code sets up an Ultimate Express server, a high-performance framework. It includes a comprehensive middleware stack for handling CORS, cookies, JSON and URL-encoded bodies, and static files. It also integrates the Inertia.js middleware and registers application routes. A global error handler is implemented for robust error management. ```typescript import express from "ultimate-express"; import cors from "cors"; import cookieParser from "cookie-parser"; import inertia from "./app/middlewares/inertia"; import Web from "./routes"; require("dotenv").config(); // Import View service for template compilation import "./app/services/View"; // Create Ultimate Express instance (6-10x faster than Express.js) const webserver = express(); // Middleware stack webserver.use(cors()); // Enable CORS webserver.use(cookieParser()); // Parse cookies webserver.use(express.json()); // Parse JSON bodies webserver.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies // Serve static files from public folder webserver.use(express.static("public")); // Apply Inertia middleware webserver.use(inertia()); // Register routes webserver.use(Web); const PORT = parseInt(process.env.PORT) || 5555; // Global error handler webserver.use((err: any, req: any, res: any, next: any) => { console.error(err); if (err.code === "SQLITE_ERROR") { res.status(500); } res.json({ error: err.message, code: err.code }); }); // Start server webserver.listen(PORT, () => { console.log(`🚀 LiteX Server running at http://localhost:${PORT}`); console.log(`⚡ Environment: ${process.env.NODE_ENV || "development"}`); console.log(`🌟 Ready to serve requests!`); }); // Graceful shutdown process.on("SIGTERM", () => { console.info("SIGTERM signal received."); process.exit(0); }); ``` -------------------------------- ### Schedule Cron Job for Command Source: https://github.com/arghoritma/litex/blob/main/README.md This example shows how to schedule a custom command to run at a specific time using cron. The command is executed from the build directory of the application. Ensure the path to your application's build directory is correct. ```bash # Run command every day at midnight 0 0 * * * cd /path/to/your/app/build && node commands/SendDailyEmails.js ``` -------------------------------- ### Clear Build Cache in LiteX Source: https://github.com/arghoritma/litex/blob/main/DEVELOPMENT.md Commands to clear the build cache for Vite and TypeScript, which can help resolve issues related to outdated build artifacts. This involves removing specific directories used by Vite and the build process. ```bash # Clear Vite cache rm -rf node_modules/.vite # Clear TypeScript cache rm -rf build/ ``` -------------------------------- ### Quick Parallel Test Benchmark (Bash/PowerShell) Source: https://github.com/arghoritma/litex/blob/main/benchmark/QUICK-START.md Menjalankan tiga benchmark framework secara paralel menggunakan skrip PowerShell. Metode ini paling cepat dengan waktu eksekusi sekitar 30 detik dan cocok untuk mendapatkan hasil cepat dengan resource sharing antar tes. ```bash cd benchmark powershell -ExecutionPolicy Bypass -File quick-parallel-test.ps1 ``` -------------------------------- ### Clone LiteX Repository Source: https://github.com/arghoritma/litex/blob/main/dist/views/index.html Command to clone the LiteX project from its GitHub repository. This is the initial step for setting up the project locally. ```bash git clone https://github.com/arghoritma/litex.git ``` -------------------------------- ### Batch File Benchmark (Batch) Source: https://github.com/arghoritma/litex/blob/main/benchmark/QUICK-START.md Menjalankan benchmark menggunakan file batch (.bat), yang tidak memerlukan instalasi PowerShell. Metode ini sederhana dan mudah dijalankan, dengan perkiraan waktu eksekusi sekitar 90 detik. ```batch cd benchmark run-all-benchmarks.bat ``` -------------------------------- ### Smooth Scrolling for Anchor Links (JavaScript) Source: https://github.com/arghoritma/litex/blob/main/resources/views/index.html Enables smooth scrolling animation when clicking on anchor links (links starting with '#'). It prevents the default jump behavior and scrolls the target element into view with a smooth animation. ```javascript // Smooth scrolling for anchor links document.querySelectorAll('a[href^="#"].forEach((anchor) => { anchor.addEventListener("click", function (e) { e.preventDefault(); const target = document.querySelector(this.getAttribute("href")); if (target) { target.scrollIntoView({ behavior: "smooth", block: "start", }); } }); }); ``` -------------------------------- ### NPM Scripts Benchmark (Bash) Source: https://github.com/arghoritma/litex/blob/main/benchmark/QUICK-START.md Menjalankan benchmark menggunakan skrip NPM yang terintegrasi dalam proyek. Tersedia opsi untuk menjalankan tes secara paralel (cepat) dengan `npm run benchmark:quick` atau sekuensial (akurat) dengan `npm run benchmark`. ```bash cd benchmark npm run benchmark:quick # Paralel (cepat) npm run benchmark # Sequential (akurat) ``` -------------------------------- ### Sequential Test Benchmark (Bash/PowerShell) Source: https://github.com/arghoritma/litex/blob/main/benchmark/QUICK-START.md Menjalankan benchmark framework satu per satu menggunakan skrip PowerShell. Metode ini paling akurat dengan waktu eksekusi sekitar 90 detik dan menyimpan hasil ke dalam file. ```bash cd benchmark powershell -ExecutionPolicy Bypass -File run-all-benchmarks.ps1 ``` -------------------------------- ### Run Database Migrations (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command executes pending database migrations using the Knex.js query builder. Ensure that Knex is configured correctly and the database connection details are set in the .env file. ```bash npx knex migrate:latest ``` -------------------------------- ### Express Route Definitions with TypeScript Source: https://context7.com/arghoritma/litex/llms.txt Defines authentication and protected routes for an Express application using TypeScript. It utilizes the 'ultimate-express' router and applies an authentication middleware to protected routes. This setup separates public and private endpoints, enhancing application security and organization. ```typescript import { Router } from "ultimate-express"; import AuthController from "./app/controllers/AuthController"; import Auth from "./app/middlewares/auth"; // Authentication routes (public) const authRoutes = Router(); authRoutes.get("/login", AuthController.loginPage); authRoutes.post("/login", AuthController.processLogin); authRoutes.get("/register", AuthController.registerPage); authRoutes.post("/register", AuthController.processRegister); authRoutes.get("/logout", AuthController.logout); authRoutes.get("/google/redirect", AuthController.redirect); authRoutes.get("/google/callback", AuthController.googleCallback); authRoutes.get("/forgot-password", AuthController.forgotPasswordPage); authRoutes.post("/forgot-password", AuthController.sendResetPassword); authRoutes.get("/reset-password/:id", AuthController.resetPasswordPage); authRoutes.post("/reset-password", AuthController.resetPassword); // Protected routes (requires authentication) const protectedRoutes = Router(); protectedRoutes.use(Auth); // Apply Auth middleware to all routes protectedRoutes.get("/", AuthController.homePage); protectedRoutes.get("/profile", AuthController.profilePage); protectedRoutes.post("/change-profile", AuthController.changeProfile); protectedRoutes.post("/change-password", AuthController.changePassword); protectedRoutes.delete("/users", AuthController.deleteUsers); // Main router const router = Router(); router.use("/auth", authRoutes); router.use("/protected", protectedRoutes); export default router; ``` -------------------------------- ### Build and Run Production Docker (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command builds the production Docker image and runs it using a separate Docker Compose file for production environments. It assumes a 'docker-compose.prod.yml' file is configured. ```bash docker-compose -f docker-compose.prod.yml up -d --build ``` -------------------------------- ### Smooth Scrolling for Anchor Links (JavaScript) Source: https://github.com/arghoritma/litex/blob/main/dist/views/index.html JavaScript code that implements smooth scrolling for anchor links (links starting with '#'). It prevents the default jump behavior and smoothly scrolls the page to the target element. This requires the target elements to have corresponding IDs. ```javascript // Smooth scrolling for anchor links document.querySelectorAll('a[href^="#"]').forEach((anchor) => { anchor.addEventListener("click", function (e) { e.preventDefault(); const target = document.querySelector(this.getAttribute("href")); if (target) { target.scrollIntoView({ behavior: "smooth", block: "start", }); } }); }); ``` -------------------------------- ### User Registration with TypeScript Source: https://context7.com/arghoritma/litex/llms.txt Handles the creation of new user accounts. It normalizes the email, hashes the password using the Authenticate service, inserts the user into the database via the DB service, and creates a session. It also includes error handling for duplicate emails and a handler to display the registration page, redirecting authenticated users. ```typescript import AuthController from "./app/controllers/AuthController"; import { Request, Response } from "./type"; import { randomUUID } from "crypto"; import DB from "./app/services/DB"; import Authenticate from "./app/services/Authenticate"; // POST /auth/register handler async function processRegister(request: Request, response: Response) { let { email, password, name } = request.body; // Normalize email email = email.toLowerCase(); try { // Create user object with hashed password const user = { id: randomUUID(), email: email, name: name, password: await Authenticate.hash(password), is_verified: false, is_admin: false, created_at: Date.now(), updated_at: Date.now() }; // Insert into database await DB.table("users").insert(user); // Create session and redirect to protected area return Authenticate.process(user, request, response); // This creates a session token, sets JWT cookie, redirects to /protected } catch (error) { // Handle duplicate email (UNIQUE constraint violation) return response .cookie("error", "Email already registered", { maxAge: 3000 }) .redirect("/auth/register"); } } // Display registration page async function registerPage(request: Request, response: Response) { // Redirect if already authenticated if (request.cookies.auth_token) { return response.redirect("/protected"); } return response.inertia("auth/register"); } ``` -------------------------------- ### Build for Production (Bash) Source: https://github.com/arghoritma/litex/blob/main/README.md This command compiles the LiteX application for production. It cleans the build directory, builds frontend assets using Vite, compiles TypeScript, and copies necessary files to the build directory. ```bash npm run build ``` -------------------------------- ### Create Post Controller Source: https://github.com/arghoritma/litex/blob/main/README.md This TypeScript code defines a controller for managing blog posts. It includes methods for fetching posts, displaying a creation form, and storing new posts. It utilizes the 'DB' service for database interactions and 'response.inertia' for rendering views. ```typescript import { Request, Response } from "../../type"; import DB from "../services/DB"; class Controller { public async index(request: Request, response: Response) { const posts = await DB.from("posts"); return response.inertia("posts/index", { posts }); } public async create(request: Request, response: Response) { return response.inertia("posts/create"); } public async store(request: Request, response: Response) { const { title, content } = request.body; await DB.table("posts").insert({ title, content, created_at: Date.now(), updated_at: Date.now(), }); return response.redirect("/posts"); } } export default new Controller(); ``` -------------------------------- ### Environment Configuration Variables Source: https://context7.com/arghoritma/litex/llms.txt A sample .env file illustrating required environment variables for application configuration. It covers settings for the port, node environment, database connection, JWT secret, Google OAuth credentials, email (SMTP) settings, optional Redis configuration, application URL, and API keys. ```dotenv # .env file PORT=5555 VITE_PORT=3000 NODE_ENV=development # Database DB_CONNECTION=development # JWT JWT_SECRET=your-secret-key-change-this-in-production # Google OAuth GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=your-client-secret GOOGLE_REDIRECT_URI=http://localhost:5555/auth/google/callback # Email (Gmail SMTP) USER_MAILER=your-email@gmail.com PASS_MAILER=your-app-specific-password # Redis (optional) REDIS_HOST=localhost REDIS_PORT=6379 # Application APP_URL=http://localhost:5555 TITLE=LiteX Application # API Keys (optional) DRIPSENDER_API_KEY=your-dripsender-api-key ``` -------------------------------- ### Build Specific Frontend or Backend Components Source: https://context7.com/arghoritma/litex/llms.txt Commands to build only the backend or frontend parts of the application. 'npm run build:server' compiles the backend code, and 'npm run build:vite' builds the frontend assets using Vite. ```bash # Build only backend npm run build:server # Build only frontend npm run build:vite ``` -------------------------------- ### Create Database Migration with Knex CLI (Bash) Source: https://context7.com/arghoritma/litex/llms.txt This command uses the Knex.js command-line interface to generate a new SQL migration file. This is the first step in defining or modifying your database schema. ```bash npx knex migrate:make create_posts_table ``` -------------------------------- ### Send Welcome Email with Nodemailer (TypeScript) Source: https://context7.com/arghoritma/litex/llms.txt This function sends a welcome email to a new user upon registration. It utilizes Nodemailer and Gmail SMTP, requiring the sender's email and application URL from environment variables. The email includes a greeting and a link to the platform's dashboard. ```typescript import Mailer from "./app/services/Mailer"; // Send welcome email async function sendWelcomeEmail(user: any) { await Mailer.sendMail({ from: process.env.USER_MAILER, to: user.email, subject: "Welcome to LiteX!", html: `

Welcome ${user.name}!

Thank you for registering on our platform.

Your account has been created successfully.

Go to Dashboard ` }); } ``` -------------------------------- ### Create Controller CLI Command Source: https://github.com/arghoritma/litex/blob/main/README.md This command generates a new controller file within the application's controller directory. It includes basic CRUD methods by default. Ensure you replace 'ControllerName' with your desired controller name. ```bash node litex make:controller ControllerName ``` ```bash node litex make:controller UserController ``` -------------------------------- ### Create Svelte Component for Blog Post List Source: https://github.com/arghoritma/litex/blob/main/README.md This Svelte component displays a list of blog posts. It accepts an array of posts as a prop and renders each post's title and content. It also includes a link to create a new post. This component is intended for use with a frontend framework like Inertia.js. ```svelte

Blog Posts

Create Post
{#each posts as post}

{post.title}

{post.content}

{/each}
``` -------------------------------- ### Create Svelte Component for New Post Form Source: https://github.com/arghoritma/litex/blob/main/README.md This Svelte component provides a form for creating a new blog post. It uses Inertia.js for handling form submission. The component includes input fields for the post title and content, and a submit button. Upon submission, it sends a POST request to the '/posts' endpoint with the form data. ```svelte

Create New Post

``` -------------------------------- ### User List with Search and Pagination (TypeScript) Source: https://context7.com/arghoritma/litex/llms.txt Provides a function to fetch and display a list of users with advanced filtering, searching, and pagination capabilities using TypeScript. It constructs database queries dynamically based on user input for search terms and filters (e.g., verified, unverified, admin). The results are then rendered using Inertia, including pagination metadata. ```typescript // GET /protected/ - Homepage with user list async function homePage(request: Request, response: Response) { const page = parseInt(request.query.page as string) || 1; const search = (request.query.search as string) || ""; const filter = (request.query.filter as string) || "all"; // Build query let query = DB.from("users").select("*"); // Apply search across multiple columns if (search) { query = query.where(function () { this.where("name", "like", `%${search}%`) .orWhere("email", "like", `%${search}%`) .orWhere("phone", "like", `%${search}%`); }); } // Apply filters if (filter === "verified") { query = query.where("is_verified", true); } else if (filter === "unverified") { query = query.where("is_verified", false); } else if (filter === "admin") { query = query.where("is_admin", true); } // Get total count for pagination const countQuery = query.clone(); const total = await countQuery.count("* as count").first(); // Get paginated results const users = await query .orderBy("created_at", "desc") .offset((page - 1) * 10) .limit(10); // Render with Inertia return response.inertia("home", { users, total: total.count, page, search, filter, perPage: 10, totalPages: Math.ceil(total.count / 10) }); } ``` -------------------------------- ### Create 'posts' Table Schema with Knex Source: https://context7.com/arghoritma/litex/llms.txt A TypeScript migration script using Knex.js to create a 'posts' table with various columns including id, user_id, title, content, slug, is_published, created_at, and updated_at. It also defines a foreign key constraint and indexes for performance. ```typescript // Migration example: migrations/20231201000000_create_posts_table.ts import { Knex } from "knex"; export async function up(knex: Knex): Promise { await knex.schema.createTable("posts", function (table) { table.uuid("id").primary().notNullable(); table.uuid("user_id").notNullable(); table.string("title", 255).notNullable(); table.text("content").notNullable(); table.string("slug", 255).unique().notNullable(); table.boolean("is_published").defaultTo(false); table.bigInteger("created_at").notNullable(); table.bigInteger("updated_at").notNullable(); // Foreign key table.foreign("user_id").references("users.id").onDelete("CASCADE"); // Indexes table.index("user_id"); table.index("slug"); table.index("is_published"); }); } export async function down(knex: Knex): Promise { await knex.schema.dropTable("posts"); } ``` -------------------------------- ### Database Service Operations with Knex.js Source: https://context7.com/arghoritma/litex/llms.txt Demonstrates CRUD operations, filtering, pagination, and connection switching using the Knex.js query builder within the LiteX framework. Supports multi-stage connection management. ```typescript import DB from "./app/services/DB"; // Query users with filters and pagination const page = 1; const search = "john"; const users = await DB.from("users") .select("*") .where(function () { this.where("name", "like", `%${search}%`) .orWhere("email", "like", `%${search}%`) .orWhere("phone", "like", `%${search}%`); }) .where("is_verified", true) .orderBy("created_at", "desc") .offset((page - 1) * 10) .limit(10); // Insert a new user const newUser = await DB.table("users").insert({ id: randomUUID(), email: "user@example.com", password: hashedPassword, name: "John Doe", created_at: Date.now(), updated_at: Date.now() }); // Update user profile await DB.from("users") .where("id", userId) .update({ name: "Jane Doe", email: "jane@example.com", phone: "+1234567890" }); // Delete users by IDs await DB.from("users").whereIn("id", [id1, id2, id3]).delete(); // Get single user const user = await DB.from("users").where("email", "user@example.com").first(); // Count records const total = await DB.from("users").count("* as count").first(); // Switch to different database connection const stagingDB = DB.connection("staging"); const products = await stagingDB("products").select("*"); ``` -------------------------------- ### Create Posts Table Migration Source: https://github.com/arghoritma/litex/blob/main/README.md This TypeScript code defines a database migration to create the 'posts' table. It specifies columns for id, title, content, and timestamps. The 'up' function creates the table, and the 'down' function drops it. ```typescript import { Knex } from "knex"; export async function up(knex: Knex): Promise { await knex.schema.createTable("posts", function (table) { table.increments("id").primary(); table.string("title").notNullable(); table.text("content").notNullable(); table.bigInteger("created_at"); table.bigInteger("updated_at"); }); } export async function down(knex: Knex): Promise { await knex.schema.dropTable("posts"); } ``` -------------------------------- ### Request Storage Access Source: https://github.com/arghoritma/litex/blob/main/dist/views/inertia.html This snippet demonstrates requesting storage access from the user. It uses the `requestStorageAccess()` API and logs whether access was granted or denied, allowing for appropriate handling of storage-related operations based on user consent. ```javascript document.requestStorageAccess().then( () => { console.log("Storage access granted"); }, () => { console.error("Storage access denied"); } ); ``` -------------------------------- ### Password Hashing and Authentication with PBKDF2 Source: https://context7.com/arghoritma/litex/llms.txt Implements secure password handling using PBKDF2 with automatic salt generation. Includes functions for hashing, comparing passwords, and managing user authentication flows like login and logout. ```typescript import Authenticate from "./app/services/Authenticate"; import { Request, Response } from "./type"; // Hash a password before storing const plainPassword = "MySecurePassword123"; const hashedPassword = await Authenticate.hash(plainPassword); // Returns: "3f2a1b4c5d6e7f8g:9h0i1j2k3l4m5n6o7p8q9r0s1t2u3v4w5x6y7z8a9b0c..." // Format: salt:hash (PBKDF2 with 100,000 iterations, SHA512, 16-byte salt) // Verify password during login const isValid = await Authenticate.compare( "MySecurePassword123", storedHash ); // Returns: true if password matches, false otherwise // Complete login flow async function processLogin(request: Request, response: Response) { const { email, password } = request.body; // Find user by email or phone const user = await DB.from("users").where("email", email).first(); if (!user) { return response .cookie("error", "Email not registered", { maxAge: 3000 }) .redirect("/auth/login"); } // Verify password const passwordMatch = await Authenticate.compare(password, user.password); if (passwordMatch) { // Create session and redirect return Authenticate.process(user, request, response); } else { return response .cookie("error", "Incorrect password", { maxAge: 3000 }) .redirect("/auth/login"); } } // Logout user async function logout(request: Request, response: Response) { await Authenticate.logout(request, response); // Deletes session from database, clears cookie, redirects to login } ``` -------------------------------- ### Inertia.js Middleware for Server-Side Rendering Source: https://context7.com/arghoritma/litex/llms.txt This middleware adds an `inertia` method to the response object, enabling seamless integration of server-side rendering with client-side navigation using Inertia.js. It handles both initial page loads and Inertia XHR requests, merging user data and error messages into the response props. Dependencies include `view` service. ```typescript import { view } from "./app/services/View"; // Middleware: app/middlewares/inertia.ts function inertia() { return (req, res, next) => { // Add inertia() method to response object res.inertia = async (component, inertiaProps = {}, viewProps = {}) => { const url = `//${req.get("host")}${req.originalUrl}`; // Merge props with user data and error messages let props = { user: req.user || {}, ...inertiaProps, ...viewProps, error: null }; // Handle error messages from cookies if (req.cookies && req.cookies.error) { props.error = req.cookies.error; res.cookie("error", "", { maxAge: 0 }); } // Build Inertia response object const inertiaObject = { component: component, props: props, url: url, version: "1.0.0" }; // Check if this is an Inertia XHR request if (!req.header("X-Inertia")) { // Initial page load - render full HTML const html = await view("inertia.html", { page: JSON.stringify(inertiaObject), title: process.env.TITLE || "LiteX Application" }); return res.type("html").send(html); } // Inertia XHR request - return JSON only res.setHeader("Vary", "Accept"); res.setHeader("X-Inertia", "true"); res.setHeader("X-Inertia-Version", "1.0.0"); return res.json(inertiaObject); }; next(); }; } // Use in controllers async function profilePage(request: Request, response: Response) { const user = request.user; // Renders Svelte component with props return response.inertia("profile", { user, pageTitle: "User Profile" }); // Component: resources/js/Pages/profile.svelte // Props available in Svelte: user, pageTitle, error } // Example with data fetching async function homePage(request: Request, response: Response) { const page = parseInt(request.query.page as string) || 1; const search = (request.query.search as string) || ""; const users = await DB.from("users") .select("*") .where("name", "like", `%${search}%`) .orderBy("created_at", "desc") .offset((page - 1) * 10) .limit(10); return response.inertia("home", { users, page, search }); } ```