Back to Documentation
2-design.md
Markdown Document
Modified: 1/9/2026
Size: 17.3 KB
This document serves as the comprehensive architectural blueprint and design specification for the AudivaMax platform. It details the system's core features, user interface guidelines, technical stack including the Next.js and Micro-ORM implementation, and the strict monorepo dependency rules tailored for a scalable audiobook streaming service.
# AudivaMax Design Document
## 1. Executive Summary
AudivaMax aims to be a premium audiobook streaming and marketplace platform, delivering a user experience and feature set comparable to Audible. The platform will focus on high-quality audio content, seamless discovery, and a user-centric library management system.
## 2. Core Features & Functional Requirements
### 2.1. User Authentication & Accounts
- **Sign Up / Login:** Support for Email/Password and Social Login (Google, Facebook, Apple).
- **User Profiles:** Manage personal details, payment methods, and billing addresses.
- **Membership Tiers:**
- _Free Tier:_ Browse catalog, purchase titles individually.
- _Premium Tier (Subscription):_ Monthly credits, access to a Plus catalog (unlimited streaming of select titles), exclusive discounts.
### 2.2. Content Discovery (Storefront)
- **Homepage:**
- **Hero Carousel:** Featured new releases and promotional banners.
- **Curated Lists:** "New York Times Bestsellers," "Trending Now," "Editor's Picks."
- **Personalization:** "Because you listened to..." recommendations based on listening history.
- **Browsing:** Navigation by Genre (Sci-Fi, Romance, Thriller, Non-fiction), Author, and Narrator.
- **Search:** robust elastic search with auto-complete, filtering by duration, language, and rating.
### 2.3. Product Detail Page (PDP)
- **Metadata:** High-res cover art, Title, Subtitle, Author, Narrator, Series info, Length, Release Date, Publisher.
- **Audio Sample:** One-click play button for a 5-minute preview.
- **Purchase Options:** "Buy with 1 Credit" vs. "Buy for 0".
- **Reviews & Ratings:** 5-star rating system with written reviews.
- **Wishlist:** "Add to Wishlist" functionality.
### 2.4. My Library
- **Cloud Library:** All purchased/added titles accessible from any device.
- **Filtering & Sorting:** Sort by Recent, Title, Author, Length. Filter by "Not Started," "In Progress," "Finished."
- **Collections:** User-created folders/collections to organize books.
### 2.5. Audio Player (Web & Mobile)
- **Playback Controls:** Play/Pause, Rewind 30s, Fast Forward 30s.
- **Variable Speed:** 0.5x to 3.5x playback speed.
- **Synchronization:** "Whispersync" capability—progress saved to the cloud and synced across devices.
- **Chapters:** View and navigate by chapter title.
- **Bookmarks:** Add notes/bookmarks at specific timestamps.
- **Sleep Timer:** Auto-stop after 15m, 30m, 60m, or end of chapter.
## 3. UI/UX Design
### 3.1. Design Philosophy
- **Clean & Content-Focused:** Minimalist interface that puts the book cover art and details front and center.
**- **Accessibility:** Adherence to WCAG 2.1 AA standards, high contrast ratios, screen reader compatibility, and clear typography.
### 3.2. Color Palette
- **Primary:** Deep Purple (#4B0082) - Evokes creativity and luxury.
- **Secondary:** Golden Amber (#FFBF00) - For Call-to-Action buttons (Buy, Play), similar to Audible's distinct orange but unique to AudivaMax.
- **Backgrounds:** Light Off-White (#F5F5F5) for content areas, Dark Charcoal (#121212) for footers/dark mode.
### 3.3. Typography
- **Headings:** Serif font (e.g., Merriweather) for a literary feel.
- **Body:** Sans-serif font (e.g., Inter or Roboto) for readability on screens.
## 4. Technical Architecture
### 4.1. Frontend
- **Framework:** Next.js (React) for SEO benefits and server-side rendering.
- **State Management:** Redux Toolkit or React Query for caching API responses.
- **Styling:** Tailwind CSS for rapid, responsive design.
### 4.2. Backend
**- **API:** Node.js with Express (RESTful).
**- **Security:** Helmet for header security, express-rate-limit for DDoS protection, and strict CORS policies.
- **Database:**
- _PostgreSQL:_ For relational data (Users, Orders, Book Metadata).
- _Redis:_ For caching sessions and frequently accessed data.
- **Search Engine:** Elasticsearch or Algolia for fast, typo-tolerant search results.
### 4.3. Infrastructure & Media
- **Storage:** PostgreSQL database for hosting audio files and cover art.
- **CDN:** CloudFront to deliver static assets and media globally with low latency.
- **Streaming:** HLS (HTTP Live Streaming) for adaptive bitrate streaming to prevent buffering.
**- **Observability:** Centralized logging via ELK Stack or Datadog; Error tracking via Sentry.
## 5. Roadmap
### Phase 1: MVP
- User Auth & Library.
- Basic Storefront (Search & Browse).
- Individual Purchases.
- Web Player.
### Phase 2: Growth
- Subscription/Credit System.
- Mobile Apps (iOS/Android).
- Recommendations Engine.
- Social Sharing features.
**### Phase 3: Scale & Intelligence**
**- AI-driven Recommendations (Vector Search).**
**- Community Features (Book Clubs, Friend Feeds).**
**- Internationalization (i18n).**
## 6. Admin Panel Design
The Admin Panel at `audivamax.com/admin` is designed to be a high-productivity internal tool for managing the platform's data, mimicking the modularity and efficiency of the Python Django Admin framework.
### 6.1. Core Architectural Pillars
- **Automatic Introspection:** The interface is dynamically generated based on data models, minimizing the need for custom UI development for new features.
- **Action-Oriented UI:** Built for bulk operations and rapid data entry.
- **Model Registry Pattern:** Centralized configuration (`AdminConfig`) defines how models are displayed, filtered, and searched.
### 6.2. Technical Specification
- **Frontend Framework:** Next.js (TypeScript) using a component-based architecture.
**- **Data Grids:** Powered by TanStack Table for sorting, filtering, and pagination.
- **State Management:**
- **URL-as-State:** Filters, search queries, and pagination are synchronized with URL parameters for deep-linking and bookmarking.
- **Zustand/Context API:** For global state like user permissions and system notifications.
- **Security & RBAC:**
- Granular Role-Based Access Control (View, Add, Change, Delete) enforced at both the API and UI levels.
- Session management via secure HTTP-only cookies and JWT.
- **Dynamic Query Builder:** Backend service that translates URL query parameters (e.g., `?price__gte=100`) into database queries.
- **Audit Logging:** A dedicated `admin_log` system tracks every change (who, what, when, and a JSON diff of changes).
### 6.3. Interface & Functional Views
- **Dashboard (The Index):** Provides a high-level overview of all registered apps and models with quick-access buttons for adding or changing records.
- **Model Change List:**
- **Search Bar:** Full-text search across pre-defined `search_fields`.
- **Sidebar Filters:** Dynamic filters for dates, booleans, and foreign key relationships.
- **Action Menu:** Dropdown for bulk operations (e.g., "Delete selected", "Export to CSV").
- **Model Change Form:**
- **Fieldsets:** Logical grouping of fields for better readability.
- **Inlines:** Allows editing of related objects (e.g., Book Chapters) directly on the parent record's page.
- **Rich Widgets:** Integrated rich text editors, date/time pickers, and searchable AJAX-powered dropdowns for foreign keys.
### 6.4. User Experience (UX)
- **Breadcrumbs:** Clear navigation path for deep nesting.
- **Recent Actions:** A sidebar widget showing the current user's most recent modifications.
- **Responsive Design:** Optimized for desktop and tablet usage to allow for management on-the-go.
## 7. Target Architecture
**Overview:** Next.js web storefront (SEO), Express + Mikro-ORM backend, Expo mobile, pnpm + Turborepo, and a strict rule that ORM entities never leak into web/mobile while DTO/Zod/OpenAPI types are shared.
**Project Scope:** Audio books catalog, browse and sales web app, with mobile app.
- **Backend:** Node.js + Express + Mikro-ORM + TypeScript
- **Frontend:** Next.js + TypeScript
- **Monorepo Stack:** Turborepo, pnpm
- **Shared Logic:** A dedicated package for Mikro-ORM Entities and Zod Schemas.
- _Share:_ Zod schemas / DTOs / OpenAPI types across apps (safe and highly valuable).
- _Share:_ Entity definitions across backend packages (safe if backend-only).
- _Constraint:_ Frontend/mobile must NOT import ORM entities directly.
### 7.1. Technology Stack
#### Web (`apps/web`)
- **Tech:** Next.js + TypeScript.
- **Focus:** SEO-first pages (catalog, audiobook detail, author/genre pages).
- **Data Access:** Calls backend via `packages/client` (typed) or direct fetch, using shared DTO types from `packages/contracts`.
- **Restrictions:** Never imports `packages/db`.
#### API (`apps/api`)
- **Tech:** Express + TypeScript.
- **Focus:** Auth, catalog, purchases, entitlements, playback authorization.
- **Data Access:** Imports `db` package (entities/migrations) and `contracts` package (DTOs).
#### Mobile (`apps/mobile`)
- **Tech:** Expo / React Native + TypeScript.
- **Data Access:** Uses `packages/client` + `packages/contracts`.
- **Restrictions:** Never imports `packages/db`.
#### Database (`packages/db`)
- **Content:** Mikro-ORM entities, migrations, repositories.
- **Access:** Server-only (importable only by `apps/api` and later `apps/worker`).
#### Contracts (`packages/contracts`)
- **Content:** Zod schemas for requests/responses.
- **Types:** Inferred TS types (`z.infer<typeof Schema>`).
- **Future:** Optional OpenAPI generator.
### 7.2. Folder Structure (Final)
```text
audivamax.com/
├── apps/
│ ├── api/ # Express API (controllers/routes)
│ ├── web/ # Next.js storefront (SEO + checkout UI)
│ └── mobile/ # React Native / Expo (listeners)
├── packages/
│ ├── db/ # Mikro-ORM config, entities, migrations (server-only)
│ ├── contracts/ # Zod schemas + inferred TS types (shared)
│ ├── config/ # shared eslint/tsconfig/prettier
│ ├── ui/ # optional shared UI components (web/mobile aware)
│ └── client/ # optional typed API client wrapper (shared)
├── turbo.json
├── pnpm-workspace.yaml
└── package.json
```
### 7.3. Strict Dependency Rules
To prevent future maintenance issues, we enforce strict boundaries:
**Allowed Imports:**
- `apps/web` → `packages/contracts`, `packages/client`, `packages/ui`, `packages/config`
- `apps/mobile` → `packages/contracts`, `packages/client`, `packages/ui`, `packages/config`
- `apps/api` → `packages/contracts`, `packages/db`, `packages/config`
**Forbidden Imports:**
- `apps/web` importing anything from `packages/db`
- `apps/mobile` importing anything from `packages/db`
- `packages/client` importing anything from `packages/db`
**Enforcement:**
- Use ESLint `no-restricted-imports` in `packages/config`.
- Make `packages/db` explicitly “server-only”.
### 7.4. Package Responsibilities and Contents
#### `packages/contracts` (Shared, Safe)
- **Purpose:** Contracts-first design; the only shared “truth” across apps.
- **Include:**
- `auth.ts`: `LoginRequestSchema`, `LoginResponseSchema`
- `catalog.ts`: `AudiobookListQuerySchema`, `AudiobookDetailResponseSchema`
- `purchase.ts`: `CreateCheckoutSessionRequestSchema`, `PurchaseReceiptSchema`
- `playback.ts`: `PlaybackAuthorizeRequestSchema`, `PlaybackAuthorizeResponseSchema`
- **Output:** `export type LoginRequest = z.infer<typeof LoginRequestSchema>;` etc.
#### `packages/db` (Server-Only)
- **Include:**
- Entities: `User`, `Audiobook`, `Author`, `Chapter`, `Order`, `Entitlement`
- Mikro-ORM config and migration setup
- Repositories/services that are DB-specific
#### `packages/client` (Shared)
- **Purpose:** Typed API calls with shared DTOs.
- **Include:**
- `createApiClient(baseUrl, tokenProvider)`
- Methods calling `/v1/...` endpoints
- Validating responses with Zod (optional but strongly recommended)
#### `packages/ui` (Optional)
- Cross-platform component library (minimal: buttons, typography, spacing tokens).
#### `packages/config`
- `tsconfig.base.json`
- ESLint config
- Prettier config
- Import restriction rules to prevent db leakage
### 7.5. “Server-only” Hardening for `packages/db`
**7.5.1. Package.json Constraints**
- Mark it `private: true`.
- Add explicit exports that discourage misuse.
**7.5.2. Tooling Enforcement**
- ESLint restrictions (strongest practical control).
- Optionally: Create a `packages/db/src/index.server.ts` and only expose that entrypoint, forbidding it outside `apps/api` / `apps/worker`.
### 7.6. API Design Basics
Version from day one:
- `GET /v1/audiobooks?query=&genre=&cursor=...`
- `GET /v1/audiobooks/:id`
- `GET /v1/authors/:id`
- `POST /v1/auth/login`
- `POST /v1/checkout/create-session` (Stripe)
- `POST /v1/webhooks/stripe`
- `GET /v1/me/library`
- `POST /v1/playback/authorize` → returns signed CDN URL (short TTL)
_Mobile and web use the same endpoints._
### 7.7. Media Delivery
**Strategy:** Do not stream audio from Express in production.
- **Storage:** Object storage (m4b on audivamax.com/etc.)
- **CDN:** CloudFront/Cloudflare
- **Authorization:** `POST /v1/playback/authorize` returns:
- A signed URL to the audio file, or
- A signed URL to an HLS playlist
### 7.8. Turborepo Pipeline
Typical tasks: `lint`, `typecheck`, `build`, `test`.
- Ensure `contracts` and `db` build first, then apps.
### 7.9. Next Steps (Highest Leverage)
1. Create `packages/contracts` first and define core DTOs.
2. Build `apps/api` endpoints around those DTOs.
3. Implement `packages/client` so both web and mobile call the API consistently.
4. Build the Next.js catalog pages (SSG/ISR) off `/v1/audiobooks` and `/v1/audiobooks/:id`.
5. Add purchases + entitlements + playback authorization.
### 7.10. Operational Configuration
**Build System:**
- **Tools:** `pnpm` workspace + `turbo` repo.
- **Pipeline:** `contracts` -> `db` -> `client` -> `apps`.
- **Script:** `doc/build.sh` automates the install, build, and restart process.
**Deployment (PM2):**
- **Configuration:** `ecosystem.config.js`.
- **Services:**
- `audivamax-api`: Runs the backend (`apps/api`).
- `audivamax-web`: Runs the frontend (`apps/web`).
- `audivamax-admin`: Runs the admin panel (`apps/admin`).
- **Ports:**
- Frontend (Web): **3016** (Production).
- Admin Panel: **3017** (Production).
- Backend (API): **5000** (Default).
## 8. Database Schema
The following schema describes the PostgreSQL database structure as defined in `packages/db` using Mikro-ORM.
### 8.1. Core Entities
#### User
Represents a registered user in the system.
- **id**: `uuid` (PK)
- **username**: `string` (Unique)
- **email**: `string` (Unique)
- **password**: `string` (Hashed)
- **role**: `enum` ('user', 'admin') - Default: 'user'
- **credits**: `number` - Default: 0
- **subscriptionTier**: `enum` ('none', 'premium') - Default: 'none'
- **subscriptionPlan**: `enum` ('none', 'premium_plus_monthly', 'premium_plus_annual') - Default: 'none'
- **subscriptionStatus**: `enum` ('active', 'canceled', 'past_due', 'none') - Default: 'none'
- **nextBillingDate**: `date` (Nullable)
- **createdAt**: `date`
- **updatedAt**: `date`
#### Author
Represents an author of a book.
- **id**: `uuid` (PK)
- **name**: `string`
- **bio**: `text` (Nullable)
#### Narrator
Represents a narrator of an audiobook.
- **id**: `uuid` (PK)
- **name**: `string`
- **bio**: `text` (Nullable)
#### Genre
Represents a genre or category for books.
- **id**: `uuid` (PK)
- **name**: `string` (Unique)
#### Book
Represents an audiobook in the system.
- **id**: `uuid` (PK)
- **title**: `string`
- **subtitle**: `string` (Nullable)
- **description**: `text` (Nullable)
- **duration**: `number` (Seconds, Nullable)
- **releaseDate**: `date` (Nullable)
- **publisher**: `string` (Nullable)
- **narratorBy**: `string` (Nullable, text representation if Entity not present)
- **price**: `decimal(10, 2)` - Default: 0.00
- **coverImage**: `blob` (Buffer, Nullable)
- **audioUrl**: `string` (Nullable)
- **sampleUrl**: `string` (Nullable)
- **rank**: `number` (Nullable)
- **sku**: `string` (Nullable)
- **author**: `FK` -> `Author` (Nullable)
- **narrator**: `FK` -> `Narrator` (Nullable)
- **createdAt**: `date`
- **updatedAt**: `date`
- **Relations**:
- `genres`: Many-to-Many -> `Genre`
### 8.2. Commerce & Library
#### Order
Represents a purchase order made by a user.
- **id**: `uuid` (PK)
- **user**: `FK` -> `User`
- **book**: `FK` -> `Book` (On Delete: Cascade)
- **amount**: `decimal(10, 2)`
- **currency**: `string` - Default: 'USD'
- **status**: `string` - Default: 'pending' (pending, completed, failed)
- **stripeSessionId**: `string` (Nullable)
- **createdAt**: `date`
- **updatedAt**: `date`
#### UserLibrary
Tracks a user's ownership and progress of a book.
- **id**: `uuid` (PK)
- **user**: `FK` -> `User`
- **book**: `FK` -> `Book` (On Delete: Cascade)
- **status**: `enum` ('Not Started', 'In Progress', 'Finished') - Default: 'Not Started'
- **progressSeconds**: `number` - Default: 0
- **lastListenedAt**: `date` (Nullable)
- **createdAt**: `date`
- **updatedAt**: `date`
#### Message
Represents a direct message between users (or admin-user).
- **id**: `uuid` (PK)
- **sender**: `FK` -> `User`
- **recipient**: `FK` -> `User`
- **subject**: `string` (Nullable)
- **body**: `text`
- **isRead**: `boolean` - Default: false
- **createdAt**: `date`
- **updatedAt**: `date`
This is a read-only view of 2-design.md. Changes must be made in the source repository.