From 3ebfdf25598c83da4874c165dad32949363a6e7c Mon Sep 17 00:00:00 2001 From: BroUnion Date: Mon, 30 Mar 2026 12:02:06 +0000 Subject: [PATCH] docs: update README and CODEBASE_MAP with new features, error classes, and documentation structure --- CODEBASE_MAP.md | 148 ++++++++-- README.md | 711 ++++++++++++++++++++++++++++++++++++------------ 2 files changed, 669 insertions(+), 190 deletions(-) diff --git a/CODEBASE_MAP.md b/CODEBASE_MAP.md index 3cde298..c981e62 100644 --- a/CODEBASE_MAP.md +++ b/CODEBASE_MAP.md @@ -2,16 +2,6 @@ > Last updated: 2026-03-30 -## Canonical Orientation Files - -Use these as the official project index set: - -1. `NOTICE.md` — backbone summary and navigation entry point. -2. `README.md` — product overview and onboarding. -3. `CODEBASE_MAP.md` — architecture and package map (this file). -4. `docs/README.md` — complete documentation map. -5. `docs/guides/provider-capabilities-and-rollout.md` — provider limitations and rollout strategy. - ## What is BetterBase? AI-native Backend-as-a-Service platform built with Bun. Define your backend in TypeScript using the Convex-inspired IaC layer, or use traditional Drizzle + Hono patterns. @@ -120,6 +110,7 @@ Scans `betterbase/` directory, registers functions | `generators/drizzle-schema-gen.ts` | Generate Drizzle schema | | `generators/migration-gen.ts` | Generate SQL migrations | | `generators/api-typegen.ts` | Generate TypeScript types | +| `errors.ts` | Error classes with suggestions | | `cron.ts` | `cron()` scheduled functions | --- @@ -133,13 +124,83 @@ React admin dashboard for self-hosted management. | Page | Route | Description | |------|-------|-------------| | Overview | `/` | Metrics, charts, activity | +| Setup | `/setup` | Initial setup | +| Login | `/login` | Authentication | +| NotFound | `/*` | 404 page | | Projects | `/projects` | List all projects | | Project Detail | `/projects/:id` | Project settings | | Project Functions | `/projects/:id/functions` | Serverless functions | +| Project IaC Functions | `/projects/:id/iac/functions` | IaC function management | +| Project IaC Schema | `/projects/:id/iac/schema` | IaC schema view | +| Project IaC Jobs | `/projects/:id/iac/jobs` | IaC job history | +| Project IaC Query | `/projects/:id/iac/query` | IaC query diagnostics | +| Project IaC Realtime | `/projects/:id/iac/realtime` | IaC realtime settings | +| Project Database | `/projects/:id/database` | Database management | +| Project Auth | `/projects/:id/auth` | Auth configuration | +| Project Env | `/projects/:id/env` | Environment variables | +| Project Webhooks | `/projects/:id/webhooks` | Project webhooks | +| Project Users | `/projects/:id/users` | Project user management | +| Project User | `/projects/:id/users/:userId` | User detail page | +| Project Realtime | `/projects/:id/realtime` | Realtime settings | +| Project Observability | `/projects/:id/observability` | Observability metrics | | Storage | `/storage` | Storage buckets | +| Storage Bucket | `/storage/:bucketId` | Bucket details | | Logs | `/logs` | Request logs | +| Function Invocations | `/functions` | Function invocation logs | +| Webhook Deliveries | `/webhook-deliveries` | Webhook delivery logs | +| Team | `/team` | Team management | | Audit | `/audit` | Audit log | +| Observability | `/observability` | System observability | | Settings | `/settings` | Instance settings | +| Settings SMTP | `/settings/smtp` | SMTP configuration | +| Settings API Keys | `/settings/api-keys` | API key management | +| Settings Notifications | `/settings/notifications` | Notification settings | +| Settings Inngest | `/settings/inngest` | Inngest dashboard | + +### UI Components + +| Component | Description | +|-----------|-------------| +| label | Label component | +| tooltip | Tooltip component | +| scroll-area | Scroll area wrapper | +| separator | Vertical/horizontal separator | +| popover | Popover component | +| switch | Toggle switch | +| textarea | Text area input | +| progress | Progress bar | +| skeleton | Loading skeleton | +| sheet | Slide-out panel | +| badge | Status badge | +| collapsible | Collapsible content | +| Avatar | User avatar | +| ConfirmDialog | Confirmation dialog | +| LiveLogStream | Live log streaming | +| CommandPalette | Command palette (Ctrl+K) | +| ErrorBoundary | Error boundary wrapper | + +### Hooks + +| Hook | Description | +|------|-------------| +| useLogStream | Live log streaming hook | +| useGlobalMetrics | Global metrics hook | +| useTheme | Theme management hook | + +### Libs + +| File | Description | +|------|-------------| +| query-keys.ts | TanStack Query keys | +| inngest-client.ts | Inngest client | +| api.ts | API client | +| utils.ts | Utility functions | + +### Layouts + +| Layout | Description | +|--------|-------------| +| AppLayout | Main application layout | ### Tech Stack @@ -298,7 +359,8 @@ betterbase/ │ │ │ │ ├── provider-prompts.ts # Database provider selection │ │ │ │ ├── route-scanner.ts # Hono route scanning │ │ │ │ ├── schema-scanner.ts # Drizzle schema scanning -│ │ │ │ └── scanner.ts # Schema scanner core +│ │ │ │ └── scanner.ts # Schema scanner core +│ │ │ │ │ └── spinner.ts # Spinner utilities │ │ └── test/ # CLI tests (30+ test files) │ │ │ ├── client/ # @betterbase/client - TypeScript SDK @@ -650,6 +712,24 @@ Betterbase uses [Inngest](https://www.inngest.com/) for durable workflows and ba --- +## Documentation (docs/) + +Comprehensive documentation for BetterBase. + +| Directory | Content | +|-----------|---------| +| `docs/getting-started/` | Installation, quick start, your first project | +| `docs/features/` | Authentication, database, storage, realtime, webhooks, functions, RLS, GraphQL | +| `docs/core/` | Core modules documentation (overview, config, providers, middleware, etc.) | +| `docs/client/` | Client SDK documentation | +| `docs/guides/` | Deployment, scaling, monitoring, production checklist | +| `docs/iac/` | Infrastructure as Code documentation (schema, functions, client hooks, etc.) | +| `docs/api-reference/` | REST API, GraphQL API, CLI commands, Client SDK reference | +| `docs/templates/` | Template documentation | +| `docs/examples/` | Example projects (ecommerce, blog, chat-app, todo-app) | + +--- + ## packages/core `@betterbase/core` - Core backend engine with all server-side functionality. @@ -1324,6 +1404,15 @@ Realtime subscriptions module for WebSocket-based live data updates. ### IaC Client Modules (NEW - Phase 3) +#### [`src/iac/provider.tsx`](packages/client/src/iac/provider.tsx) +**Purpose:** React context provider for IaC functions. +- **Exports:** `BetterBaseReactProvider`, `useIaC` +- **Key Features:** + - Wraps React app with BetterBase context + - `useIaC()` hook returns query/mutation/action functions + - Configurable base URL and auth token + - Compatible with TanStack Query + #### [`src/iac/hooks.ts`](packages/client/src/iac/hooks.ts) **Purpose:** React hooks for IaC functions (query, mutation). - **Exports:** `useQuery`, `useMutation`, `useAction` @@ -1652,11 +1741,29 @@ The authentication template with full BetterAuth integration. - **Path:** `templates/auth/` - **Purpose:** Projects requiring authentication out of the box - **Includes:** - - Pre-configured BetterAuth setup + - Pre-configured BetterAuth setup (`src/auth/index.ts`, `src/auth/types.ts`) - Email/password authentication - Social OAuth providers (configurable) - Session management - - Auth middleware examples + - Auth middleware (`src/middleware/auth.ts`) + - Auth routes (`src/routes/auth.ts`, `src/routes/auth-example.ts`) + - Auth schema (`src/db/auth-schema.ts`, `src/db/schema.ts`) + - Drizzle adapter integration (`src/db/index.ts`) + - `betterbase.config.ts`, `drizzle.config.ts`, `package.json` + +### templates/iac + +The IaC project template with Convex-inspired patterns. + +- **Path:** `templates/iac/` +- **Purpose:** Projects using the Infrastructure as Code approach +- **Includes:** + - `betterbase/schema.ts` - Schema definition + - `betterbase/queries/` - Query functions + - `betterbase/mutations/` - Mutation functions + - `betterbase/actions/` - Action functions + - `betterbase/cron.ts` - Scheduled functions + - `betterbase.config.ts` - Project configuration --- @@ -2086,18 +2193,16 @@ bun test All notable changes to BetterBase will be documented in this file. -### Recent Updates (2026-03-29) +### Recent Updates (2026-03-30) #### Documentation Updates -- **CODEBASE_MAP.md**: Updated to reflect new IaC realtime modules, server routes, and client features +- **CODEBASE_MAP.md**: Updated with new IaC error classes, generators, docs directory, and IaC template #### New Modules Added -- **IaC Storage**: Added `iac/storage/storage-ctx.ts` for file operations in IaC functions -- **IaC Realtime**: Added `iac/realtime/` subdirectory with table dependency inference, invalidation manager, and subscription tracker -- **Server Routes**: Added project-scoped routes (database, functions, users, env, auth-config, webhooks, realtime, iac) -- **Server Libs**: Added webhook-logger.ts, function-logger.ts, audit.ts -- **CLI Utils**: Added api-client.ts, credentials.ts -- **Client IaC**: Added paginated-query.ts for cursor-based pagination +- **IaC Errors**: Added `iac/errors.ts` with error classes (IaCError, ValidationError, DatabaseError, AuthError, NotFoundError) and formatError utility +- **IaC Generators**: Added code generators (drizzle-schema-gen.ts, migration-gen.ts, api-typegen.ts) +- **Documentation**: Added docs/ directory with comprehensive documentation structure +- **IaC Template**: Added `templates/iac/` for Convex-inspired IaC pattern projects #### Package Updates - **packages/cli**: 30+ test files, 9 utility modules @@ -2110,3 +2215,4 @@ All notable changes to BetterBase will be documented in this file. ## License BetterBase is released under the MIT license. + diff --git a/README.md b/README.md index de6f957..9dab5f2 100644 --- a/README.md +++ b/README.md @@ -1,274 +1,647 @@
-# Betterbase +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/weroperking/Betterbase) -**Enterprise Backend Platform for Product Teams** +``` +██████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗ ███████╗ ██████╗ ██╗ ██╗███████╗ +██╔══██╗██║ ██║██╔════╝██╔═══██╗██║ ██╔════╝ ██╔═══██╗██║ ██║██╔════╝ +██████╔╝███████║██║ ██║ ██║██║ █████╗ ██║ ██║██║ █╗ ██║█████╗ +██╔══██╗██╔══██║██║ ██║ ██║██║ ██╔══╝ ██║ ██║██║███╗██║██╔══╝ +██║ ██║██║ ██║╚██████╗╚██████╔╝███████╗███████╗ ╚██████╔╝╚███╔███╔╝███████╗ +╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚══╝ ╚══╝ ╚══════╝ +``` -*AI-native backend development with IaC workflows, realtime APIs, auth, storage, and deployment flexibility.* +**The AI-Native Backend-as-a-Service Platform** -[Documentation](./docs/README.md) • [Self Hosting](./SELF_HOSTED.md) • [Contributing](./CONTRIBUTING.md) • [Notice](./NOTICE.md) +Blazing-fast backend development with Sub-100ms Local Dev — Built on Bun + SQLite, deploy anywhere with PostgreSQL support. -
+*Database • Authentication • Realtime Subscriptions • Storage • Serverless Functions • Vector Search* ---- +**Last Updated: 2026-03-30** -## Executive Summary + -Betterbase is an enterprise-ready backend platform designed for teams that need to move fast without sacrificing governance, security posture, or infrastructure portability. +--- -It combines: +## Why Choose Betterbase? -- **Developer velocity** with Bun + TypeScript workflows. -- **Backend consistency** through Infrastructure-as-Code patterns. -- **Operational control** through self-hosted and cloud-capable deployment modes. -- **Scalable architecture** across authentication, database access, storage, realtime, and background automation. +``` +┌─────────────────────────────────────────────────────────────────────────────────────────────┐ +│ ✦ BETTERBASE ARCHITECTURE ✦ │ +├─────────────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────────────────────┐ ┌─────────┐ │ +│ │ Frontend │ │ │ │ │ │ +│ │ (React, Vue, │──────────▶│ BETTERBASE CORE │──────────▶│ DB │ │ +│ │ Mobile, │ │ │ │ SQLite/ │ │ +│ │ Svelte) │ │ Auth │ Realtime │ Storage │ │ Postgres│ │ +│ └──────────────┘ │ RLS │ Vector │ Fns │ └─────────┘ │ +│ └──────────────────────────────┘ │ │ +│ │ │ │ +│ ┌──────▼──────┐ │ │ +│ │ IaC │◀──── (Infrastructure as Code) │ │ +│ │ Layer │ │ │ +│ │ Convex-ish │ │ │ +│ └───────────┘ │ │ +│ │ │ +│ ┌──────▼──────┐│ +│ │ Inngest ││ +│ │ Workflows ││ +│ └────────────┘│ +└─────────────────────────────────────────────────────────────────────────────────────────────┘ +``` -If your organization wants a modern backend platform with strong engineering ergonomics and clear pathways to production hardening, Betterbase is built for that mission. +| | TraditionalBAAS | Betterbase | +|--|------------------|------------| +| ⚡ | Slow local dev | **Sub-100ms dev** with Bun + SQLite | +| 🗄️ | Black box DB | **Full PostgreSQL** with raw SQL access | +| 🔍 | Basic search | **Full-text + Vector search** built-in | +| 🚀 | Cloud lock-in | **Self-host anywhere** with Docker | +| 📊 | Limited analytics | **Full observability** out of the box | +| 🔐 | Closed source | **100% open source** - deploy anywhere | --- -## Who Betterbase Is For +## Quick Start -Betterbase is optimized for: +```bash +# Install the CLI +bun install -g @betterbase/cli -- **Platform Engineering teams** building internal developer platforms. -- **Product Engineering teams** shipping SaaS features rapidly. -- **Enterprise organizations** requiring policy-driven architecture and auditable change management. -- **Teams migrating from fragmented backend stacks** to a unified, opinionated foundation. +# Create a new project (IaC mode - recommended) +bb init my-app +cd my-app +bun install +bb dev +``` ---- +Your project structure: -## Core Capabilities +``` +my-app/ +├── betterbase/ +│ ├── schema.ts # Define tables (Convex-style) +│ ├── queries/ # Read functions (auto-subscribe) +│ ├── mutations/ # Write functions (transactions) +│ └── actions/ # Side-effects (scheduled, HTTP) +├── betterbase.config.ts # Optional config +└── package.json +``` -### 1) Infrastructure-as-Code (IaC) Application Layer +### Define Your Schema -Model backend behavior in TypeScript with a structured pattern for: +Edit `betterbase/schema.ts`: -- Schema definitions (`defineSchema`, `defineTable`) -- Queries and mutations -- Actions and scheduled jobs -- Module-level organization for larger codebases +```typescript +import { defineSchema, defineTable, v } from "@betterbase/core/iac" -### 2) Data Platform +export const schema = defineSchema({ + users: defineTable({ + name: v.string(), + email: v.string(), + }).uniqueIndex("by_email", ["email"]), + + posts: defineTable({ + title: v.string(), + content: v.string(), + published: v.boolean(), + authorId: v.id("users"), + }).index("by_author", ["authorId"]), +}) +``` -- SQL-first architecture -- Migration workflows -- Full-text and vector search options -- Provider-aware behavior with documented rollout limitations and capabilities +### Write Functions -### 3) Auth and Access Control +```typescript +// betterbase/queries/posts.ts +import { query } from "@betterbase/core/iac" -- BetterAuth-based authentication workflows -- Session and provider integrations -- Row-level access patterns and security-oriented practices +export const listPosts = query({ + args: { published: v.optional(v.boolean()) }, + handler: async (ctx, args) => { + return ctx.db.query("posts") + .filter("published", "eq", args.published ?? true) + .order("desc") + .take(50) + }, +}) +``` -### 4) Realtime and API Surfaces +```typescript +// betterbase/mutations/posts.ts +import { mutation } from "@betterbase/core/iac" + +export const createPost = mutation({ + args: { + title: v.string(), + content: v.string(), + authorId: v.id("users"), + }, + handler: async (ctx, args) => { + return ctx.db.insert("posts", { + ...args, + published: false, + }) + }, +}) +``` -- Realtime subscriptions -- REST and GraphQL support -- SDK-first integration model for frontend and service clients +### Run -### 5) Async and Event Workloads +```bash +bb dev +``` -- Webhooks -- Background functions -- Durable orchestration through Inngest-compatible flows +Your backend runs at `http://localhost:3000`. The dashboard is at `http://localhost:3001`. -### 6) Deployment Flexibility +--- -- Local development -- Docker and containerized deployments -- Self-hosted enterprise topology options +## Key Features + +| Feature | Description | +|---------|-------------| +| **IaC Layer** | Convex-inspired: define schema + functions in TypeScript | +| **Auto-Realtime** | Queries auto-subscribe to changes | +| **Type Safety** | Full TypeScript inference, no code generation needed | +| **Migrations** | Automatic diff + apply on `bb dev` | +| **Raw SQL** | `ctx.db.execute()` for complex queries | +| **Full-Text Search** | PostgreSQL GIN indexes via `ctx.db.search()` | +| **Vector Search** | pgvector + HNSW for embeddings | +| **Serverless Functions** | Deploy custom API functions | +| **Storage** | S3-compatible object storage | +| **Webhooks** | Event-driven with signed payloads | +| **Background Jobs** | Durable workflows via Inngest | +| **RLS** | Row-level security policies | +| **Branching** | Preview environments per branch | --- -## Architecture at a Glance - -```text -Clients (Web, Mobile, Services) - │ - ▼ - Betterbase Runtime Layer - ├─ Auth + Sessions - ├─ API Surface (REST/GraphQL) - ├─ Realtime - ├─ Function Runtime - ├─ Storage Integration - └─ IaC-Defined Data Access - │ - ▼ - Database Providers (SQLite/PostgreSQL/MySQL/libSQL) - │ - ▼ - Operations Layer (Migrations, Monitoring, Deployment, Automation) -``` - -For detailed architecture and module mapping, start here: - -1. [`NOTICE.md`](./NOTICE.md) -2. [`CODEBASE_MAP.md`](./CODEBASE_MAP.md) -3. [`docs/README.md`](./docs/README.md) -4. [`docs/guides/provider-capabilities-and-rollout.md`](./docs/guides/provider-capabilities-and-rollout.md) +## Betterbase vs Convex + +| Feature | Convex | Betterbase | +|---------|--------|------------| +| Database | Black box | Full PostgreSQL | +| Raw SQL | Not available | `ctx.db.execute()` | +| Full-Text Search | Not built-in | PostgreSQL FTS | +| Vector Search | Limited | pgvector + HNSW | +| Self-Hosting | Not supported | Docker to your infra | +| Migration | — | `bb migrate from-convex` | + +**Betterbase gives you Convex simplicity with full SQL power.** --- -## Quick Start (IaC Workflow) +## Inngest Integration -### Prerequisites +Betterbase uses [Inngest](https://www.inngest.com/) for durable workflows and background jobs. -- Bun (recommended runtime/package manager) -- Docker (recommended for production-like local testing) +### Deployment Modes -### Bootstrap a Project +| Mode | Inngest Backend | Used By | +|------|----------------|---------| +| Cloud | `https://api.inngest.com` | BetterBase Cloud offering | +| Self-Hosted | `http://inngest:8288` | Docker deployment | +| Local Dev | `http://localhost:8288` | Development and testing | + +### Environment Variables ```bash -bun install -g @betterbase/cli -bb init my-app -cd my-app -bun install -bb dev +# For local development +INNGEST_BASE_URL=http://localhost:8288 + +# For self-hosted production +INNGEST_BASE_URL=http://inngest:8288 +INNGEST_SIGNING_KEY=your-signing-key +INNGEST_EVENT_KEY=your-event-key ``` -### Typical Project Layout +### Features + +- **Webhook Delivery**: Retryable, observable webhook delivery with automatic backoff +- **Notification Rules**: Cron-based metric polling with fan-out notifications +- **Background Exports**: Async CSV export with progress tracking + +--- + +## Project Structure -```text +Betterbase supports two patterns: + +### 1. IaC Pattern (Recommended) + +``` my-app/ ├── betterbase/ -│ ├── schema.ts -│ ├── queries/ -│ ├── mutations/ -│ ├── actions/ -│ └── cron.ts +│ ├── schema.ts # defineSchema() + defineTable() +│ ├── queries/ # query() functions +│ ├── mutations/ # mutation() functions +│ ├── actions/ # action() functions +│ └── cron.ts # scheduled functions +├── betterbase.config.ts # Optional config +└── package.json +``` + +### 2. Original Pattern (Advanced) + +``` +my-app/ +├── src/ +│ ├── db/ +│ │ ├── schema.ts # Drizzle schema +│ │ └── migrate.ts # Migration runner +│ ├── routes/ # Hono routes +│ └── functions/ # Serverless functions ├── betterbase.config.ts └── package.json ``` -### Sample Schema (TypeScript) +Both patterns work together. Add `betterbase/` to any existing project. -```ts -import { defineSchema, defineTable, v } from "@betterbase/core/iac" +--- -export const schema = defineSchema({ - users: defineTable({ - name: v.string(), - email: v.string(), - }).uniqueIndex("by_email", ["email"]), +## CLI Reference + +| Command | Description | +|---------|-------------| +| `bb init [name]` | Create new project | +| `bb dev` | Start dev server | +| `bb iac sync` | Sync IaC schema | +| `bb iac analyze` | Analyze query performance | +| `bb migrate` | Run migrations | +| `bb generate types` | Generate TypeScript types | + +--- + +## Client SDK + +```bash +bun add @betterbase/client +``` + +```typescript +import { createClient } from '@betterbase/client' + +const client = createClient({ + baseUrl: 'http://localhost:3000', +}) + +// Use IaC functions +const { data: posts } = await client.bff.queries.posts.listPosts({}) + +// Mutations +await client.bff.mutations.posts.createPost({ + title: 'Hello', + content: 'World', + authorId: 'user-123', }) ``` --- -## Enterprise Operating Model +## Deployment -### Governance and Change Management +### Local -- IaC-centered definitions support repeatable, reviewable backend changes. -- Migration and config workflows can be integrated into CI/CD controls. -- Repository-level standards support branch-driven release discipline. +```bash +bb dev +``` -### Security Posture +### Docker -- Auth integration patterns with provider-level controls. -- Row-level access strategies for tenant and user isolation. -- Guidance for security and production hardening in dedicated docs. +```bash +docker-compose up -d +``` -### Reliability and Observability +### Self-Hosted -- Designed for structured monitoring and operational playbooks. -- Deployment and scaling guides included for production planning. -- Supports separation of concerns between product feature teams and platform operations. +See [SELF_HOSTED.md](SELF_HOSTED.md) for full documentation. ---- +```typescript +database: { + provider: 'neon', + connectionString: process.env.NEON_CONNECTION_STRING +} +``` -## Documentation Map +### Turso (libSQL) -### Getting Started +Best for edge deployments and distributed databases. + +```typescript +database: { + provider: 'turso', + connectionString: process.env.TURSO_DATABASE_URL, + authToken: process.env.TURSO_AUTH_TOKEN +} +``` -- [`docs/getting-started/installation.md`](./docs/getting-started/installation.md) -- [`docs/getting-started/quick-start.md`](./docs/getting-started/quick-start.md) -- [`docs/getting-started/your-first-project.md`](./docs/getting-started/your-first-project.md) +### MySQL -### IaC Documentation +Best for legacy applications or MySQL preference. -- [`docs/iac/01-introduction.md`](./docs/iac/01-introduction.md) -- [`docs/iac/02-schema.md`](./docs/iac/02-schema.md) -- [`docs/iac/03-functions.md`](./docs/iac/03-functions.md) -- [`docs/iac/14-migration-from-convex.md`](./docs/iac/14-migration-from-convex.md) +```typescript +database: { + provider: 'mysql', + connectionString: process.env.MYSQL_URL +} +``` -### Core and Features +### PlanetScale (MySQL-compatible) -- [`docs/core/overview.md`](./docs/core/overview.md) -- [`docs/features/database.md`](./docs/features/database.md) -- [`docs/features/authentication.md`](./docs/features/authentication.md) -- [`docs/features/realtime.md`](./docs/features/realtime.md) -- [`docs/features/storage.md`](./docs/features/storage.md) +Best for serverless MySQL with branch-based schema changes. -### APIs and Clients +```typescript +database: { + provider: 'planetscale', + connectionString: process.env.PLANETSCALE_URL +} +``` -- [`docs/api-reference/cli-commands.md`](./docs/api-reference/cli-commands.md) -- [`docs/api-reference/rest-api.md`](./docs/api-reference/rest-api.md) -- [`docs/api-reference/graphql-api.md`](./docs/api-reference/graphql-api.md) -- [`docs/api-reference/client-sdk.md`](./docs/api-reference/client-sdk.md) +--- -### Production Guidance +## Authentication -- [`docs/guides/deployment.md`](./docs/guides/deployment.md) -- [`docs/guides/security-best-practices.md`](./docs/guides/security-best-practices.md) -- [`docs/guides/monitoring.md`](./docs/guides/monitoring.md) -- [`docs/guides/scaling.md`](./docs/guides/scaling.md) -- [`docs/guides/production-checklist.md`](./docs/guides/production-checklist.md) +### Setup BetterAuth ---- +Initialize authentication in your project: -## Deployment Modes +```bash +bb auth setup +``` -- **Local Development:** Fast feedback loops for application development. -- **Containerized:** Docker-based workflows for reproducible environments. -- **Self-Hosted Enterprise:** Internal infrastructure with security/compliance controls. +This creates `src/auth/` with default configuration. + +### Configure Providers + +Edit `src/auth/index.ts`: + +```typescript +import { betterAuth } from 'better-auth' +import { drizzleAdapter } from 'better-auth/adapters/drizzle' +import { db } from '../db' + +export const auth = betterAuth({ + database: drizzleAdapter(db, { + provider: 'sqlite' // or 'postgres', 'mysql' + }), + emailAndPassword: { + enabled: true, + requireEmailVerification: false + }, + socialProviders: { + github: { + clientId: process.env.GITHUB_CLIENT_ID, + clientSecret: process.env.GITHUB_CLIENT_SECRET + }, + google: { + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET + } + }, + session: { + expiresIn: 60 * 60 * 24 * 7, // 7 days + updateAge: 60 * 60 * 24 // 1 day + } +}) +``` + +### Row Level Security -For implementation details, see: +Betterbase integrates with database RLS for secure data access: + +```typescript +// In your schema or via CLI +bb rls add \ + --table posts \ + --name users_own_posts \ + --command SELECT \ + --check "user_id = auth.uid()" +``` -- [`SELF_HOSTED.md`](./SELF_HOSTED.md) -- [`docs/docker-setup.md`](./docs/docker-setup.md) -- [`docker-compose.production.yml`](./docker-compose.production.yml) +This ensures users can only access their own data. --- -## Repository Structure +## Ask Deepwiki -```text -betterbase/ -├── apps/ # runnable apps and test projects -├── packages/ # core packages (cli, client, core) -├── templates/ # scaffolding templates -├── docs/ # full documentation portal -├── docker-compose*.yml # deployment/topology manifests -└── turbo.json # monorepo task orchestration -``` +> *Your AI-powered development assistant, integrated directly into Betterbase.* + +Ask Deepwiki provides intelligent context for AI-assisted development: + +- **Smart Code Context**: Automatic `.betterbase-context.json` generation +- **IaC Analysis**: Understand your schema, queries, and mutations +- **Query Optimization**: Get recommendations for better performance +- **Documentation Generation**: Auto-generate docs from your code + +**Deepwiki Badge**: The badge at the top of this README links to [Ask Deepwiki](https://deepwiki.com/weroperking/Betterbase), where you can chat with an AI that understands your entire Betterbase project. + +### Using Ask Deepwiki + +1. **Development**: Get instant answers about your IaC layer +2. **Debugging**: Understand query behavior and optimization +3. **Onboarding**: New team members can ask about your architecture +4. **Refactoring**: Get AI suggestions for improving your code --- -## Development and Contribution +## Contributing + +We welcome contributions! Please follow these steps: -Please read: +### Getting Started -- [`CONTRIBUTING.md`](./CONTRIBUTING.md) -- [`docs/README.md`](./docs/README.md) +1. **Fork** the repository +2. **Clone** your fork: `git clone https://github.com/your-username/betterbase.git` +3. **Install** dependencies: `bun install` +4. **Create** a branch: `git checkout -b feature/my-feature` -Typical local workflow: +### Development Setup ```bash +# Install dependencies bun install + +# Build all packages bun run build + +# Run tests bun test + +# Run linting +bun run lint +``` + +### Project Structure + +``` +betterbase/ +├── apps/ +│ └── test-project/ # Example/test project +├── packages/ +│ ├── cli/ # @betterbase/cli +│ ├── client/ # @betterbase/client +│ └── core/ # @betterbase/core +├── templates/ # Project templates +└── turbo.json # Turborepo configuration +``` + +### Code Style + +We use Biome for code formatting and linting: + +```bash +# Format code +bun run format + +# Lint code bun run lint + +# Fix auto-fixable issues +bun run lint:fix +``` + +### Testing + +```bash +# Run all tests +bun test + +# Run tests for specific package +bun test --filter=@betterbase/cli + +# Run tests in watch mode +bun test --watch +``` + +### Commit Messages + +Follow Conventional Commits: + +``` +feat: add new feature +fix: resolve bug +docs: update documentation +refactor: restructure code +test: add tests +chore: maintenance +``` + +### Submitting Changes + +1. Push your branch: `git push origin feature/my-feature` +2. Open a **Pull Request** +3. Fill out the PR template +4. Wait for review + +--- + +## Code of Conduct + +### Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +### Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +### Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at conduct@betterbase.io. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. + +--- + +## Changelog + +All notable changes to this project will be documented in this section. + +### [1.0.0] - 2026-03-19 + +#### Added + +- **AI Context Generation**: Automatic `.betterbase-context.json` generation for AI-assisted development +- **Branch Management**: New `bb branch` command for creating isolated preview environments +- **Vector Search**: pgvector-powered similarity search with embeddings support +- **Auto-REST**: Automatic CRUD route generation from Drizzle schema +- **Enhanced CLI**: Added 12 commands including branch, webhook management, and storage operations + +#### Updated + +- Updated copyright year to 2026 +- Improved documentation with Last Updated timestamp +- Verified all features against current codebase structure +- Removed deprecated @betterbase/shared package references + +#### Security + +- Improved webhook signature verification +- Enhanced RLS policy engine + +--- + +## License + +Betterbase is open source under the [MIT License](LICENSE). + +``` +MIT License + +Copyright (c) 2026 Betterbase + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. ``` --- -## Product Positioning +## Community & Support + +### Get Help + +| Resource | Link | +|----------|------| +| **Discord** | [Discord](https://discord.gg/R6Dm6Cgy2E) | +| **GitHub Issues** | [GitHub Issues](https://github.com/weroperking/Betterbase/issues) | + +### Contribute + +| Resource | Link | +|----------|------| +| **GitHub** | [GitHub](https://github.com/weroperking/Betterbase) | +| **Contributing Guide** | [CONTRIBUTING.md](CONTRIBUTING.md) | +| **Good First Issues** | [Good First Issues](https://github.com/weroperking/Betterbase/labels/good-first-issue) | + +--- + +
-Betterbase is built to serve as a **future-facing enterprise backend foundation**: opinionated where it accelerates teams, flexible where organizations need control. +**Built with ❤️ by Weroperking** -In short: **developer speed, enterprise guardrails, production portability.** +[Website](#) • [Documentation](docs/README.md) • [Discord](https://discord.gg/R6Dm6Cgy2E) • [GitHub](https://github.com/weroperking/Betterbase) • [Twitter](#) +
\ No newline at end of file