### Quick Start MCP Server Setup Source: https://alepha.dev/docs/guides-server-mcp Sets up an Alepha application with MCP support, defining a basic tool and resource. This server will be available at /mcp endpoints. ```typescript import { t, run } from "alepha"; import { AlephaMcp, $tool, $resource } from "alepha/mcp"; import { AlephaServer } from "alepha/server"; class MyMcp { add = $tool({ description: "Add two numbers", schema: { params: t.object({ a: t.number(), b: t.number(), }), result: t.number(), }, handler: async ({ params }) => params.a + params.b, }); readme = $resource({ uri: "docs://readme", description: "Project README", mimeType: "text/markdown", handler: async () => ({ text: "# My App\nWelcome to my application.", }), }); } run( Alepha.create() .with(AlephaServer) .with(AlephaMcp) .with(MyMcp), ); ``` -------------------------------- ### Full Deployment Example Source: https://alepha.dev/docs/guides-deployment-cloudflare A complete example demonstrating setting the `DATABASE_URL` in `.env.production`, followed by building and deploying the application for Cloudflare Workers. ```bash # .env.production DATABASE_URL=d1://alepha-app:00000000-0000-0000-0000-000000000000 # Build and deploy alepha build --target=cloudflare --mode production alepha deploy ``` -------------------------------- ### Running with environment variables Source: https://alepha.dev/docs/reference-primitives-$mode Command line examples to activate the migration mode. ```bash MIGRATE=true node app.js # runs migrations, then exits MODE=MIGRATE node app.js # same effect ``` -------------------------------- ### Start Development Server Source: https://alepha.dev/docs/cli-commands-dev Basic command to initiate the development server. ```bash alepha dev ``` -------------------------------- ### Install @alepha/protobuf Source: https://alepha.dev/docs/packages-alepha-protobuf Use npm to install the @alepha/protobuf package. ```bash npm install @alepha/protobuf ``` -------------------------------- ### Usage Example Source: https://alepha.dev/docs/reference-primitives-$circuit Example of how to use the $circuit middleware with an action. ```APIDOC ## Usage Example ### Description Demonstrates how to apply the `$circuit` middleware to an action, configuring the failure threshold and reset duration. ### Code Example ```typescript import { $action, $circuit } from "alepha/server"; class PaymentController { paymentGateway: any; // Assume this is initialized elsewhere charge = $action({ use: [$circuit({ threshold: 5, reset: [30, "seconds"] })], handler: async ({ body }) => this.paymentGateway.charge(body), }); } ``` ### Explanation - The `use` array includes the `$circuit` middleware. - `threshold: 5` means the circuit will open after 5 consecutive failures. - `reset: [30, "seconds"]` sets the cooldown period to 30 seconds before attempting to transition to the half-open state. ``` -------------------------------- ### Zero Config Entry Point Source: https://alepha.dev/docs/cli-commands-dev Example of a minimal entry point file for auto-configuration. ```typescript // src/main.ts import { Alepha } from "alepha"; const alepha = Alepha.create(); await alepha.start(); ``` -------------------------------- ### Installation Source: https://alepha.dev/docs/packages-alepha-command Instructions on how to install the Alepha Command module as part of the alepha package. ```APIDOC ## Installation Part of the `alepha` package. Import from `alepha/command`. ```bash npm install alepha ``` ``` -------------------------------- ### CLI Installation and Usage Source: https://alepha.dev/llms-full.txt Commands for creating projects and running local scripts via npx. ```bash npx alepha init ``` ```bash npx alepha dev npx alepha build ``` ```bash npm run dev ``` ```bash node --version ``` -------------------------------- ### Install @alepha/ui Source: https://alepha.dev/docs/packages-alepha-ui-admin Install the @alepha/ui package using npm. ```bash npm install @alepha/ui ``` -------------------------------- ### Install @alepha/devtools Source: https://alepha.dev/docs/packages-alepha-devtools Use npm to install the @alepha/devtools package. This command is typically run once during project setup. ```bash npm install @alepha/devtools ``` -------------------------------- ### Basic Setup Source: https://alepha.dev/docs/guides-server-openapi Import the $swagger primitive and initialize it with basic info to serve Swagger UI and OpenAPI JSON. ```APIDOC ## Basic Setup ### Description Import the `$swagger` primitive and initialize it with basic info to serve Swagger UI and OpenAPI JSON. ### Method N/A ### Endpoint N/A ### Request Example ```typescript import { $swagger } from "alepha/server/swagger"; class App { docs = $swagger({ info: { title: "My API", version: "1.0.0", description: "Product catalog REST API", }, }); } ``` ### Response #### Success Response (200) - **Swagger UI**: Interactive documentation served at `/docs`. - **OpenAPI JSON**: Specification served at `/docs/json`. ``` -------------------------------- ### Define Environment Variables Source: https://alepha.dev/docs/cli-commands-dev Example content for a .env file. ```text DATABASE_URL=postgres://localhost/mydb API_KEY=secret123 ``` -------------------------------- ### Sitemap XML Example Source: https://alepha.dev/docs/cli-commands-build This is an example of the `sitemap.xml` file generated by the `--sitemap` option. It lists the URLs of your application's routes. ```xml https://myapp.com/ https://myapp.com/about ``` -------------------------------- ### Initialize Alepha Project with Testing Setup Source: https://alepha.dev/docs/cli-commands-init Use the `--test` flag to set up Vitest and create a starter test file. ```bash alepha init --test ``` -------------------------------- ### Install @alepha/bucket-s3 Source: https://alepha.dev/docs/packages-alepha-bucket-s3 Use npm to install the package as a dependency in your project. ```bash npm install @alepha/bucket-s3 ``` -------------------------------- ### Initialize OpenAPI Documentation Source: https://alepha.dev/docs/guides-server-openapi Basic setup for the $swagger primitive within an application class. ```typescript import { $swagger } from "alepha/server/swagger"; class App { docs = $swagger({ info: { title: "My API", version: "1.0.0", description: "Product catalog REST API", }, }); } ``` -------------------------------- ### Configure Cloud Platform Source: https://alepha.dev/llms-full.txt Setup platform plugins and deploy to the cloud. ```typescript import { defineConfig } from "alepha/cli/config"; import { AlephaCliPlatform } from "alepha/cli/platform"; export default defineConfig({ services: [AlephaCliPlatform], platform: { environments: { production: { adapter: "cloudflare" }, }, }, }); ``` ```bash npx alepha p up ``` ```bash npx alepha p plan ``` -------------------------------- ### Alepha package.json Scripts Source: https://alepha.dev/docs/cli-installation Example configuration for scripts in package.json after initialization. ```json { "scripts": { "dev": "alepha dev", "build": "alepha build", "verify": "alepha verify" } } ``` -------------------------------- ### Full-Stack App Development Source: https://alepha.dev/docs/cli-commands-dev Development command for projects with alepha/react installed. ```bash alepha dev # → http://localhost:5173 ``` -------------------------------- ### Initialize a New Alepha Project Source: https://alepha.dev/docs/cli-commands-init Run this command in an empty directory to start a new Alepha project with default settings. ```bash alepha init ``` -------------------------------- ### Implement MediaService with $bucket Source: https://alepha.dev/docs/reference-primitives-$bucket Example demonstrating how to define buckets for different file types and perform upload, download, and delete operations within a service class. ```ts class MediaService { images = $bucket({ name: "user-images", mimeTypes: ["image/jpeg", "image/png", "image/gif"], maxSize: 5 // 5MB limit }); documents = $bucket({ name: "documents", mimeTypes: ["application/pdf", "text/plain"], maxSize: 50 // 50MB limit }); async uploadProfileImage(file: FileLike, userId: string): Promise { const fileId = await this.images.upload(file); await this.userService.updateProfileImage(userId, fileId); return fileId; } async downloadDocument(documentId: string): Promise { return await this.documents.download(documentId); } async deleteDocument(documentId: string): Promise { await this.documents.delete(documentId); } } ``` -------------------------------- ### Install @alepha/mqtt package Source: https://alepha.dev/docs/packages-alepha-mqtt-topic Use npm to add the MQTT plugin to your project dependencies. ```bash npm install @alepha/mqtt ``` -------------------------------- ### Basic Proxy Setup Source: https://alepha.dev/docs/reference-primitives-$proxy Set up a basic proxy to forward all requests matching a path pattern to a specified target URL. ```typescript import { $proxy } from "alepha/server/proxy"; class ApiGateway { // Forward all /api/* requests to external service api = $proxy({ path: "/api/*", target: "https://api.example.com" }); } ``` -------------------------------- ### Initialize Alepha Project with React and Testing Source: https://alepha.dev/docs/cli-commands-init Combine flags to customize your project setup, such as including both React and testing. ```bash alepha init --react --test ``` -------------------------------- ### Define Project Resources Source: https://alepha.dev/docs/reference-primitives-$resource Example showing how to define multiple resources within a class, including file-based and configuration-based data. ```ts class ProjectResources { readme = $resource({ uri: "file:///readme", description: "Project README file", mimeType: "text/markdown", handler: async () => ({ text: await fs.readFile("README.md", "utf-8"), }), }); config = $resource({ uri: "config://app", name: "Application Configuration", mimeType: "application/json", handler: async () => ({ text: JSON.stringify(this.configService.getConfig()), }), }); } ``` -------------------------------- ### Run Application Source: https://alepha.dev/docs/guides-core-alepha-instance Use the run helper to start the application and handle graceful shutdown signals like SIGTERM or SIGINT. ```typescript import { run } from "alepha"; run(alepha); ``` -------------------------------- ### Server Entry Point Configuration Source: https://alepha.dev/llms-full.txt Configure the server entry point for an Alepha React application, registering modules and starting the app. ```typescript import { Alepha, run } from "alepha"; import { AppRouter } from "./AppRouter.ts"; import { CountApi } from "./CountApi.ts"; const alepha = Alepha.create({ env: { APP_NAME: "MY_APP" } }); alepha.with(CountApi); alepha.with(AppRouter); run(alepha); ``` -------------------------------- ### Navigate to Project Directory Source: https://alepha.dev/docs/guides-getting-started Change into the newly created project directory. ```bash cd my-app ``` -------------------------------- ### Install Playwright dependencies Source: https://alepha.dev/docs/guides-testing-e2e-tests Install the necessary Playwright packages and browser binaries for testing. ```bash npm install -D @playwright/test npx playwright install ``` -------------------------------- ### Install Alepha Package Source: https://alepha.dev/docs/packages-alepha-api-files Install the alepha package using npm. This is required to use the alepha/api/files module. ```bash npm install alepha ``` -------------------------------- ### $route - Import and Overview Source: https://alepha.dev/docs/reference-primitives-$route Demonstrates how to import and provides an overview of the $route primitive, highlighting its low-level nature and suggesting $action as a higher-level alternative. ```APIDOC ## $route ### Description Creates a basic endpoint. This is a low-level primitive. You probably want to use `$action` instead. ### Method Not applicable (primitive definition) ### Endpoint Not applicable (primitive definition) ### Parameters Not applicable (primitive definition) ### Request Example ```typescript import { $route } from "alepha/server"; // Example usage (conceptual, as $route is a primitive) const myRoute = $route((req, res) => { res.send("Hello from $route!"); }); ``` ### Response Not applicable (primitive definition) ``` -------------------------------- ### Initialize Alepha Project with Full UI Kit Source: https://alepha.dev/docs/cli-commands-init The `--ui` flag includes the `@alepha/ui` component library, implying React support. ```bash alepha init --ui ``` -------------------------------- ### Full Entity Schema Example Source: https://alepha.dev/docs/guides-persistence-special-columns An example demonstrating the usage of various special columns including primary key, timestamps, enum, default value, version, and soft delete within a user entity schema. ```typescript import { t } from "alepha"; import { $entity, db } from "alepha/orm"; const user = $entity({ name: "users", schema: t.object({ id: db.primaryKey(t.uuid()), email: t.email(), name: t.text(), role: t.enum(["admin", "user", "moderator"]), isActive: db.default(t.boolean(), true), createdAt: db.createdAt(), updatedAt: db.updatedAt(), deletedAt: db.deletedAt(), version: db.version(), }), indexes: [ { column: "email", unique: true }, ], }); ``` -------------------------------- ### Initialize Alepha Project Source: https://alepha.dev/llms-full.txt Commands to bootstrap a new Alepha project with various configuration options. ```bash # In an empty directory alepha init # With React support alepha init --react # With the full UI kit alepha init --ui ``` -------------------------------- ### GET /api/users Source: https://alepha.dev/docs/reference-primitives-$action Retrieves a paginated list of users. ```APIDOC ## GET /api/users ### Description Retrieves a list of users based on optional pagination parameters. ### Method GET ### Endpoint /api/users ### Parameters #### Query Parameters - **page** (number) - Optional - Page number (default: 1) - **limit** (number) - Optional - Number of items per page (default: 10) ### Response #### Success Response (200) - **users** (array) - List of user objects - **total** (number) - Total count of users #### Response Example { "users": [{"id": "1", "name": "John Doe", "email": "john@example.com"}], "total": 1 } ``` -------------------------------- ### Build and Deploy Static Sites Source: https://alepha.dev/llms-full.txt Commands for building and deploying static applications to Surge. ```bash alepha build --target=static ``` ```bash alepha build --target=static alepha deploy ``` -------------------------------- ### Build for Production Source: https://alepha.dev/llms-full.txt Commands to build and run the production bundle. ```bash npm run build ``` ```bash node dist ``` ```bash bun dist ``` -------------------------------- ### GET /docs Source: https://alepha.dev/llms-full.txt Serves the interactive Swagger UI for the API. ```APIDOC ## GET /docs ### Description Serves the interactive Swagger UI interface for exploring the API endpoints. ### Method GET ### Endpoint /docs ``` -------------------------------- ### Initialize Alepha Project with Admin Portal Source: https://alepha.dev/docs/cli-commands-init Use the `--admin` flag to include the admin portal, which implies authentication, UI, and React support. ```bash alepha init --admin ``` -------------------------------- ### Initialize Alepha Project Source: https://alepha.dev/docs/guides-getting-started Use this command to create a new Alepha project with default configurations. ```bash npx alepha@latest init my-app ``` -------------------------------- ### GET /docs/json Source: https://alepha.dev/llms-full.txt Serves the raw OpenAPI 3.0 JSON specification. ```APIDOC ## GET /docs/json ### Description Returns the full OpenAPI 3.0 specification in JSON format. ### Method GET ### Endpoint /docs/json ``` -------------------------------- ### Configure Server Entry and Modules Source: https://alepha.dev/llms.txt Use the run function to initialize modules and $module to group services. Ensure file extensions are included in imports. ```typescript // src/main.server.ts import { run } from "alepha"; import { ApiModule } from "./api/index.ts"; import { WebModule } from "./web/index.ts"; // React only run(ApiModule, WebModule); // src/api/index.ts import { $module } from "alepha"; import { UserController } from "./controllers/UserController.ts"; export const ApiModule = $module({ name: "app.api", services: [UserController], }); ``` -------------------------------- ### Initialize Alepha Project with API Module Source: https://alepha.dev/docs/cli-commands-init Use the `--api` flag to include the API module structure (`src/api/`). ```bash alepha init --api ``` -------------------------------- ### Register a Hook Source: https://alepha.dev/docs/reference-primitives-$hook Example of defining a lifecycle hook within a provider class. ```ts import { $hook } from "alepha"; class MyProvider { onStart = $hook({ name: "start", // or "configure", "ready", "stop", ... handler: async (app) => { // await db.connect(); ... } }); } ``` -------------------------------- ### Deploy and Plan Infrastructure Source: https://alepha.dev/docs/guides-getting-started Commands to deploy infrastructure or preview changes before execution. ```bash npx alepha p up ``` ```bash npx alepha p plan ``` -------------------------------- ### GET /mcp Source: https://alepha.dev/docs/guides-server-mcp Establishes an SSE (Server-Sent Events) connection for the MCP server. ```APIDOC ## GET /mcp ### Description Establishes an SSE connection to the MCP server for real-time communication with AI assistants. ### Method GET ### Endpoint /mcp ``` -------------------------------- ### GET /products/:id Source: https://alepha.dev/docs/guides-server-http-links Retrieves product details using the ProductController action. ```APIDOC ## GET /products/:id ### Description Retrieves a product by its unique identifier. ### Method GET ### Endpoint /products/:id ### Parameters #### Path Parameters - **id** (uuid) - Required - The unique identifier of the product. ### Response #### Success Response (200) - **id** (uuid) - Product ID - **name** (text) - Product name - **price** (number) - Product price ``` -------------------------------- ### Basic Form Usage with useForm Source: https://alepha.dev/docs/guides-frontend-forms Demonstrates the basic setup of a form using `useForm`, including schema definition, handler for submission, and spreading form props onto form elements. ```typescript import { t } from "alepha"; import { useForm } from "alepha/react/form"; function LoginForm() { const form = useForm({ schema: t.object({ email: t.email(), password: t.text(), }), handler: async (values) => { await api.login(values); }, }); return (
); } ``` -------------------------------- ### Error Response Format Source: https://alepha.dev/docs/guides-server-error-handling Example of the standard JSON structure returned for HTTP errors. ```json { "error": "NotFoundError", "status": 404, "message": "User not found", "requestId": "abc-123" } ``` -------------------------------- ### Initialize Alepha Project Source: https://alepha.dev/docs/cli-installation Creates a new project and adds the alepha dependency. ```bash npx alepha init ``` -------------------------------- ### Testing with MemoryDestinationProvider Source: https://alepha.dev/docs/guides-core-logging Provides an example of how to capture and assert on logs during testing using MemoryDestinationProvider. ```APIDOC ## Testing with MemoryDestinationProvider ### Description In test environments, Alepha defaults to using `MemoryDestinationProvider` to buffer logs. This snippet shows how to capture these logs in memory and assert their content in tests. ### Method Test setup and assertion ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { Alepha } from "alepha"; import { $logger, LogDestinationProvider, MemoryDestinationProvider } from "alepha/logger"; class App { log = $logger(); } test("should log info message", ({ expect }) => { const alepha = Alepha.create({ env: { LOG_LEVEL: "trace" }, }).with({ provide: LogDestinationProvider, use: MemoryDestinationProvider, }); const output = alepha.inject(MemoryDestinationProvider); const app = alepha.inject(App); app.log.info("Test log message"); expect(output.logs[0].message).toBe("Test log message"); expect(output.logs[0].level).toBe("INFO"); expect(output.logs[0].service).toBe("App"); }); ``` ### Response N/A ### Success Response (200) N/A ### Response Example N/A ``` -------------------------------- ### Initialize Alepha Project with React Support Source: https://alepha.dev/docs/cli-commands-init Use the `--react` flag to include React dependencies and the web module for full-stack applications. ```bash alepha init --react ``` -------------------------------- ### Migration Workflow Summary Source: https://alepha.dev/docs/guides-persistence-migrations Overview of commands for development and production migration workflows. ```bash # Development - automatic schema sync alepha dev # Production - explicit migration workflow alepha db migrations generate # generate migration files alepha db migrations apply --mode production # apply to production database ``` -------------------------------- ### GET /health and /healthz Source: https://alepha.dev/docs/reference-providers-serverhealthprovider Registers health check endpoints to monitor the server status. ```APIDOC ## GET /health ### Description Provides basic health information about the server. ### Method GET ### Endpoint /health ## GET /healthz ### Description Provides basic health information about the server. ### Method GET ### Endpoint /healthz ``` -------------------------------- ### Run Alepha Bundle Source: https://alepha.dev/docs/guides-deployment-bare Executes the generated server bundle using Node.js or Bun. ```bash node dist # Node.js bun dist # Bun ``` -------------------------------- ### $batch Initialization Source: https://alepha.dev/docs/reference-primitives-$batch Documentation for the $batch primitive configuration and options. ```APIDOC ## $batch ### Description Creates a batch processing primitive for efficient grouping and processing of multiple operations. ### Parameters #### Options - **schema** (TItem) - Required - TypeBox schema for validating each item added to the batch. - **handler** (Object) - Required - The batch processing handler function that processes arrays of validated items. - **maxSize** (number) - Optional - Maximum number of items to collect before automatically flushing the batch. - **maxQueueSize** (number) - Optional - Maximum number of items that can be queued in a single partition. - **maxDuration** (DurationLike) - Optional - Maximum time to wait before flushing a batch, even if it hasn't reached maxSize. - **partitionBy** (Object) - Optional - Function to determine partition keys for grouping items into separate batches. - **concurrency** (number) - Optional - Maximum number of batch handlers that can execute simultaneously. - **retry** (Object) - Optional - Retry configuration for failed batch processing operations. ``` -------------------------------- ### Import $queue Primitive Source: https://alepha.dev/docs/reference-primitives-$queue Import the $queue primitive from the alepha/queue library to start using it. ```typescript import { $queue } from "alepha/queue"; ``` -------------------------------- ### Testing Logs Source: https://alepha.dev/llms-full.txt Provides an example of how to capture and assert on logs in test environments using `MemoryDestinationProvider`. ```APIDOC ## Testing In test mode, Alepha routes logs to `MemoryDestinationProvider` by default. Logs are buffered in memory and only printed to the console if a test fails. To capture and assert on logs in tests: ```typescript import { Alepha } from "alepha"; import { $logger, LogDestinationProvider, MemoryDestinationProvider } from "alepha/logger"; class App { log = $logger(); } test("should log info message", ({ expect }) => { const alepha = Alepha.create({ env: { LOG_LEVEL: "trace" }, }).with({ provide: LogDestinationProvider, use: MemoryDestinationProvider, }); const output = alepha.inject(MemoryDestinationProvider); const app = alepha.inject(App); app.log.info("Test log message"); expect(output.logs[0].message).toBe("Test log message"); expect(output.logs[0].level).toBe("INFO"); expect(output.logs[0].service).toBe("App"); }); ``` ``` -------------------------------- ### Vercel Configuration File Source: https://alepha.dev/docs/guides-deployment-vercel Example of the generated vercel.json file used for routing and build configuration. ```json { "rewrites": [{ "source": "/(.*)", "destination": "/api/index.js" }], "buildCommand": "", "installCommand": "", "outputDirectory": "public" } ``` -------------------------------- ### CLI Command: alepha init Source: https://alepha.dev/docs/cli-commands-init Initializes a new Alepha project with optional configuration flags. ```APIDOC ## CLI Command: alepha init ### Description Initializes a new Alepha project. It creates necessary configuration files, sets up package.json, configures the package manager, installs dependencies, and creates starter files. ### Parameters #### Options - **--api** (flag) - Optional - Include API module structure (src/api/) - **--react, -r** (flag) - Optional - Include React dependencies and web module (src/web/) - **--ui** (flag) - Optional - Include @alepha/ui component library (implies --react) - **--auth** (flag) - Optional - Include authentication (implies --api --ui --react) - **--admin** (flag) - Optional - Include admin portal (implies --auth) - **--tailwind** (flag) - Optional - Include Tailwind CSS with Vite plugin (implies --react) - **--test** (flag) - Optional - Set up Vitest and create a test directory - **--pm ** (string) - Optional - Package manager to use: yarn, npm, pnpm, or bun - **--force, -f** (flag) - Optional - Override existing files ``` -------------------------------- ### Initialize Alepha Project Source: https://alepha.dev/llms-full.txt Commands to initialize a new project with optional testing and React support. ```bash alepha init --test ``` ```bash alepha init --react --test ``` -------------------------------- ### Import CloudflareQueueProvider Source: https://alepha.dev/docs/reference-providers-cloudflarequeueprovider Import the CloudflareQueueProvider class from the alepha/queue library. Ensure you have the necessary package installed. ```typescript import { CloudflareQueueProvider } from "alepha/queue"; ``` -------------------------------- ### Check Node.js Version Source: https://alepha.dev/docs/cli-installation Verifies the installed Node.js version to ensure compatibility with Alepha requirements. ```bash node --version ``` -------------------------------- ### Build with Production Mode Source: https://alepha.dev/docs/guides-deployment-cloudflare Use the `--mode` flag to specify the environment for loading `.env` files during the build process. This example loads `.env` and `.env.production`. ```bash alepha build --target=cloudflare --mode production ``` -------------------------------- ### $inject - Dependency Injection Source: https://alepha.dev/llms-full.txt Get the instance of the specified type from the context. Used for dependency injection. ```APIDOC ## $inject - Dependency Injection ### Description Get the instance of the specified type from the context. ### Import ```typescript import { $inject } from "alepha"; ``` ### Usage Example ```typescript class A { } class B { a = $inject(A); } ``` ``` -------------------------------- ### Generate Sitemap Source: https://alepha.dev/docs/cli-commands-build Build your project and generate a `sitemap.xml` file in the `dist/public/` directory. Replace `https://myapp.com` with your site's base URL. ```bash alepha build --sitemap=https://myapp.com ``` -------------------------------- ### useTheme Hook Source: https://alepha.dev/docs/reference-react-hooks-usetheme A hook to get and set the current theme, along with expert mode controls. ```APIDOC ## useTheme Hook ### Description Provides a tuple containing the current theme, a setter function, and expert mode controls for fine-grained customization. ### Import ```typescript import { useTheme } from "@alepha/ui/styles.css"; ``` ### Usage ```tsx const [theme, setTheme, expert] = useTheme(); ``` ### Returns - **theme** (string) - The current active theme. - **setTheme** (function) - A function to update the current theme. - **expert** (object) - Expert mode controls for fine-grained customization. ``` -------------------------------- ### Get a single record with error handling Source: https://alepha.dev/docs/guides-persistence-repository Retrieve a single record, throwing DbEntityNotFoundError if it does not exist. ```typescript const item = await this.repo.getOne({ where: { name: { eq: "Widget" } }, }); ``` -------------------------------- ### Initialize Alepha Project with Authentication Source: https://alepha.dev/docs/cli-commands-init The `--auth` flag includes authentication features, implying API, UI, and React support. ```bash alepha init --auth ``` -------------------------------- ### Cache Methods Source: https://alepha.dev/docs/guides-persistence-caching Available methods for interacting with the cache: `run`, `get`, `set`, `invalidate`, and `incr`. ```APIDOC ## Methods ### run Execute the handler function with caching. This is what gets called when you invoke the cache as a function. Only available when a `handler` is defined. ```typescript const result = await this.getUserData("some-uuid"); // equivalent to: const result = await this.getUserData.run("some-uuid"); ``` ### get Retrieve a cached value by key. Returns `undefined` if the key does not exist or has expired. ```typescript const value = await this.sessions.get("session-123"); ``` ### set Store a value in the cache with an optional TTL override. ```typescript await this.sessions.set("session-123", sessionData); await this.sessions.set("session-123", sessionData, [30, "minutes"]); ``` ### invalidate Remove one or more keys from the cache. Supports pattern-based invalidation with a trailing wildcard `*`. ```typescript // Invalidate a specific key await this.sessions.invalidate("session-123"); // Invalidate multiple keys await this.sessions.invalidate("session-123", "session-456"); // Pattern-based invalidation: delete all keys starting with "user:" await this.cache.invalidate("user:*"); ``` Calling `invalidate()` with no arguments deletes all entries in the cache's namespace. ### incr Atomically increment a numeric value. If the key does not exist, it is set to 0 before incrementing. ```typescript const newCount = await this.counter.incr("page-views", 1); ``` ### key Get the cache key that would be generated for the given arguments (useful for debugging). ```typescript const cacheKey = this.getUserData.key("some-uuid"); ``` ``` -------------------------------- ### Create and Render a Form with useForm Source: https://alepha.dev/docs/reference-react-hooks-useform Example of initializing useForm with a schema and handler, then rendering the form elements. Ensure the schema defines expected fields and the handler processes submitted values. ```tsx import { t } from "alepha"; const form = useForm({ schema: t.object({ username: t.text(), password: t.text(), }), handler: (values) => { console.log("Form submitted with values:", values); }, }); return (
); ``` -------------------------------- ### Import the $bucket utility Source: https://alepha.dev/docs/guides-persistence-buckets Import the $bucket utility from the alepha/bucket package to start defining buckets. ```typescript import { $bucket } from "alepha/bucket"; ``` -------------------------------- ### Build Alepha Project Source: https://alepha.dev/docs/guides-deployment-bare Bundles server and client code into an optimized output folder. ```bash alepha build ``` -------------------------------- ### Register Health Check Endpoint Source: https://alepha.dev/docs/guides-server-middlewares Adds a GET /health endpoint for load balancer and readiness probes. ```typescript import { Alepha } from "alepha"; import { AlephaServerHealth } from "alepha/server/health"; Alepha.create() .with(AlephaServerHealth) .with(App) .start(); ``` -------------------------------- ### Configure Alepha Server Entry Point Source: https://alepha.dev/llms-full.txt Sets up the server entry point for an Alepha application, running both API and Web modules. This example demonstrates how to combine different modules for a full-stack application. ```typescript // src/main.server.ts import { run } from "alepha"; import { ApiModule } from "./api/index.ts"; import { WebModule } from "./web/index.ts"; // React only run(ApiModule, WebModule); ``` -------------------------------- ### $interval - Periodic Task Execution Source: https://alepha.dev/llms-full.txt Run a function periodically using setInterval. Starts and stops with the context. ```APIDOC ## $interval - Periodic Task Execution ### Description Run a function periodically. It uses the `setInterval` internally. It starts by default when the context starts and stops when the context stops. ### Import ```typescript import { $interval } from "alepha/datetime"; ``` ### Options #### Parameters - **handler** (Object) - Required - The interval handler. - **duration** (DurationLike) - Required - The interval duration. ``` -------------------------------- ### Render Components with Alepha Source: https://alepha.dev/docs/guides-testing-react-tests Use renderWithAlepha to wrap components in the Alepha context and automatically start the instance. ```typescript import { renderWithAlepha, setupJsdomMocks } from "alepha/react/testing"; beforeAll(() => setupJsdomMocks()); test("should render greeting", async () => { const { getByText, alepha } = await renderWithAlepha(); expect(getByText("Hello, Alice")).toBeDefined(); }); ``` -------------------------------- ### Manual Lifecycle Control in Tests Source: https://alepha.dev/docs/guides-core-alepha-instance Manually start the application in test environments to verify service readiness. ```typescript test("MyService", async () => { const app = Alepha.create().with(MyService); await app.start(); const service = app.inject(MyService); expect(service.isReady).toBe(true); // await app.stop(); ← automatically called by Vitest hooks }); ``` -------------------------------- ### useForm Hook - Overview and Usage Source: https://alepha.dev/docs/reference-react-hooks-useform This snippet details the import, overview, and a basic usage example of the useForm hook. ```APIDOC ## useForm Hook ### Description Custom hook to create a form with validation and field management. It utilizes TypeBox schemas for defining structure and validation rules, offering functionalities for form submission, field creation, and value management. ### Import ```typescript import { useForm } from "alepha/react/form"; ``` ### Usage Example This example demonstrates how to initialize and use the `useForm` hook with a TypeBox schema and a submission handler. ```tsx import { t } from "alepha"; const form = useForm({ schema: t.object({ username: t.text(), password: t.text(), }), handler: (values) => { console.log("Form submitted with values:", values); }, }); return (
); ``` ### Parameters for useForm - **schema** (TypeBoxSchema) - Required - Defines the structure and validation rules for the form fields. - **handler** (function) - Required - A callback function that is executed upon successful form submission. It receives the form values as an argument. ### Form Object Properties - **props** (object) - Spread this onto the form element to bind form properties. - **input** (object) - An object containing input properties for each defined form field. Each field has its own `props` for binding to input elements. ``` -------------------------------- ### Scaffold Project with Test Support Source: https://alepha.dev/docs/guides-testing-unit-tests Use this command to initialize a new Alepha project with Vitest testing capabilities already configured. ```bash alepha init my-app --test ``` -------------------------------- ### Write end-to-end test cases Source: https://alepha.dev/docs/guides-testing-e2e-tests Example test file demonstrating page navigation and API health checks. ```typescript // e2e/home.spec.ts import { test, expect } from "@playwright/test"; test("home page loads", async ({ page }) => { await page.goto("/"); await expect(page).toHaveTitle(/My App/); }); test("API returns data", async ({ request }) => { const response = await request.get("/api/health"); expect(response.ok()).toBeTruthy(); }); ``` -------------------------------- ### Standard Node.js Deployment Source: https://alepha.dev/docs/cli-commands-build Deploy your project to any environment that runs Node.js. This involves copying the `dist/` folder to your server and running the Node.js entry point. ```bash # Copy dist/ to your server scp -r dist/ user@server:/app # On the server cd /app && node index.js ```